简体   繁体   中英

Multiple models in view ASP.NETMVC (PartialView Approach)

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.List 1[WebApplication7.Models.Person]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[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?

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>())

试试看(现在没有机器在运行vs),但是应该可以

@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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM