2

Last days I learning ASP.NET MVC. I have a problem when I would use two or more models in "master" view.

Model one:

 public class PersonController : Controller
{
    private Context ctx = new Context();
    public IEnumerable<Employer> employersCol { get;set; }
    // GET: Person]
    public ActionResult Index()
    {
        employersCol = ctx.employers.ToList();
        return View(ctx.persons.ToList());
    }
}

Model two:

 public class EmployerController : Controller
    {
        private Context ctx = new Context();
        // GET: Employer
        public ActionResult Index()
        {
            return View(ctx.employers.ToList());
        }
    }

so, now in "master" view I would to display data:

@foreach (var p in Model)
{
    @Html.DisplayFor(m => p.firstName);
    @Html.DisplayFor(m => p.lastName);
}
@Html.Partial("~/Views/Employer/_emp.cshtml")

but the Visual Studio say:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code

Additional information: The model item passed into the dictionary is of type 'System.Collections.Generic.List1[WebApplication7.Models.Person]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[WebApplication7.Models.Employer]'.

The question is: how Can I pass the type to the partial view. Maybe you prefer another approach. Hm.. maybe I have to use Ajax.. but how?

ekad
  • 14,436
  • 26
  • 44
  • 46
Alder23
  • 103
  • 5

2 Answers2

0

By default, Razor will pass the page model down to the partial. Therefore, assuming the _emp.cshtml view has a model of IEnumerable<Employee> rather than IEnumerable<Person> then you can use the overload for @Html.Partial to override the model

@Html.Partial("~/Views/Employer/_emp.cshtml", Model.Cast<Employee>())
James
  • 80,725
  • 18
  • 167
  • 237
0

Try This (dont have a machine running vs right now) but should work

@Html.Partial("~/Views/Employer/_emp.cshtml", model.Employer) ; // the property name by which u expose your model, if your model is not an Arraylist, then you need to loop through it. 
Abdul Rehman Sayed
  • 6,532
  • 7
  • 45
  • 74