简体   繁体   English

视图中的多个模型ASP.NETMVC(PartialView方法)

[英]Multiple models in view ASP.NETMVC (PartialView Approach)

Last days I learning ASP.NET MVC. 最后几天,我学习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: 但是Visual Studio说:

An exception of type 'System.InvalidOperationException' occurred in System.Web.Mvc.dll but was not handled in user code System.Web.Mvc.dll中发生类型为'System.InvalidOperationException'的异常,但未在用户代码中处理

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]'. 附加信息:传递到字典中的模型项的类型为'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? 嗯..也许我必须使用Ajax ..但是如何?

By default, Razor will pass the page model down to the partial. 默认情况下,Razor会将页面模型向下传递给局部模型。 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 因此,假设_emp.cshtml视图具有IEnumerable<Employee>模型而不是IEnumerable<Person>模型,则可以对@Html.Partial使用重载来覆盖该模型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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