Binding model to the view.
my model Person has {Id,Title,Address…etc)
In my controller I want to retrieve some fields
e.g:
var model = from p in db.Person where p.jobtype == 1
select new Person { Title = p.Title, Address = p.Address};
return View(model);
also tried to to use anonymous type and it doesn’t work:
var model = from p in db.Person where p.jobtype == 1
select new { p.Title, p.Address};
return View(model);
In my view:
@model IEnumerable<Demo.Models.Person>
@foreach (var item in Model) {
<div>@item.Title</div>} >FAILS
If I retrieve full object then it works, how do I retrieve some fields using anonymous type or\and using my model…. plz provide the correct syntax. Thanks
If your View is requiring the Model to be
Enumerablethen it needs to beAsEnumerablein your select statement.and then
Alternatively, Since you just need a list at the end of the day, and you “should” be using a ViewModel, I suggest the following.
ViewModel
Controller
View
note: I used AutoMapper in the above example
I don’t have my IDE in front of me, so I’m not sure if this is perfect.