I was intrigued by this Rachel Appel blog post that has a View that references a ViewModel, and within the View is able to access the properties across the ViewModel's multiple entities using Lambda expressions with this syntax:
@Html.EditorFor(model => model.ViewModelEntityName.Property)
I was able to access the individual ViewModel entities, but not the properties of those entities. Here is my code:
ViewModel
public class PoliciesTrustsViewModel
{
public ICollection<Insurance> Policies { get; set; } //model in partial class generated by EF database first
public ICollection<Companies> Trusts { get; set; } //model in partial class generated by EF database first
public PoliciesTrustsViewModel(ICollection<Insurance> policies, ICollection<Companies> trusts)
{
Policies = policies;
Trusts = trusts;
}
Controller
public ActionResult Create()
{
ICollection<Insurance> policies = db.Insurance.ToList();
ICollection<Companies> trusts = db.Companies.ToList();
var myViewModel = new ViewModels.PoliciesTrustsViewModel(policies, trusts);
return View(myViewModel);
}
View
I set the model reference to the ViewModel:
@model IEnumerable<TrustsInsurance.ViewModels.PoliciesTrustsViewModel>
Lambda expressions will accept the entity name but will not allow the properties within an individual entity. So
@Html.EditorFor(model => model.Policies, new { htmlAttributes = new { @class = "form-control" } })
is allowable, but
@Html.EditorFor(model => model.Policies.Property, new { htmlAttributes = new { @class = "form-control" } })
yields a "does not contain a definition" error. I tried using a @foreach (var item in Model) loop in razor as well as a number of different casts, but no sale. So how can one access properties across multiple models using lambda expressions? Any nudge in the right direction would be greatly appreciated.
@Html.EditorFor(model => model.Policies.First().Property, new { htmlAttributes = new { @class = "form-control" } })