Reputation: 51
I have two Models - Ksiazka.cs and Ludzie.cs and I have a View Wypozyczone.cshtml which presents Ludzie.cs.
Ksiazka.cs
public int Id { get; set; }
public string Nazwa { get; set; }
public string Autor { get; set; }
public int Ilosc { get; set; }
Ludzie.cs
public int Id { get; set; }
public int IdKsiazki { get; set; }
public string Imie { get; set; }
public string Nazwisko { get; set; }
public DateTime DataWyporzyczenia { get; set; }
public DateTime DataOddania { get; set; }
Ksiazka.id = Ludzie.IdKsiazki
I need to get Nazwa answering IdKsiazki.
Controler
public ActionResult Wypozyczone()
{
var model = _mojaBaza.Ludzie.ToList();
return View(model);
My view
<th>
@Html.DisplayNameFor(model => model.IdKsiazki) //I want there Nazwa
</th>
<th>
@Html.DisplayNameFor(model => model.Imie)
</th>
<th>
@Html.DisplayNameFor(model => model.Nazwisko)
</th>
<th>
@Html.DisplayNameFor(model => model.DataWyporzyczenia)
</th>
<th>
@Html.DisplayNameFor(model => model.DataOddania)
</th>
Upvotes: 0
Views: 165
Reputation: 41
If you want to use more than a model on your view, please use Tuple:
So your view should be some thing like this
@model Tuple<Ksiazka,Ludzie>
<th>
@Html.DisplayNameFor(tuple => tuple.Item1.Nazwa ) //I want there Nazwa
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item2.Imie)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item2.Nazwisko)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item2.DataWyporzyczenia)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item2.DataOddania)
</th>
Upvotes: 0
Reputation: 27039
Even though, in your question, you have indicated 2 models, you do not need two models. Your problem is your current entity model does not have the one-to-one navigational property for the relationship.
Just listen to your code because it is telling you what it needs: Your view is asking for more information from another class so your view needs a model which has info from both of the models you have. In your Ludzie
class you need a navigation property so it can hold the information for Ksiazka
:
public class Ludzie
{
// You need this property
public Ksiazka Ksiazka { get; set; }
}
Then when you load Ludzie
, you will have access to Ksiazka
. Then in your view you can do this:
// You can access Nazwa
@Html.DisplayNameFor(model => model.Ksiazka.Nazwa)
You can read more here on navigation properties.
Upvotes: 0
Reputation: 32443
Create another class(some kind of viewmodel) which represents data you want
public class LudzieKsiazka
{
public Ludzie Ludzie { get; set; }
public Ksiazka Ksiazka { get; set; }
}
In controller create this "viewmodel"
public ActionResult Wypozyczone()
{
var model = _mojaBaza.Ludzie.FirstOrDefault();
var ksiazka = _mojaBaza.Ksiazka.FirstOrDefault(kz => kz.Id = model.IdKsiazki);
var viewmodel = new LudzieKsiazka { Ludzie = model, Ksiazka = kziazka };
return View(viewmodel);
}
Then in view use this "viewmodel"
<th>
@Html.DisplayNameFor(model => model.Ksiazka.Nazwa)
</th>
Upvotes: 1