[英]Multiple models in view ASP.NETMVC (PartialView Approach)
最后几天,我学习ASP.NET MVC。 我在“主”视图中使用两个或多个模型时遇到问题。
模型一:
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());
}
}
模型二:
public class EmployerController : Controller
{
private Context ctx = new Context();
// GET: Employer
public ActionResult Index()
{
return View(ctx.employers.ToList());
}
}
因此,现在在“主”视图中,我将显示数据:
@foreach (var p in Model)
{
@Html.DisplayFor(m => p.firstName);
@Html.DisplayFor(m => p.lastName);
}
@Html.Partial("~/Views/Employer/_emp.cshtml")
但是Visual Studio说:
System.Web.Mvc.dll中发生类型为'System.InvalidOperationException'的异常,但未在用户代码中处理
附加信息:传递到字典中的模型项的类型为'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]”。
问题是:如何将类型传递给局部视图。 也许您更喜欢另一种方法。 嗯..也许我必须使用Ajax ..但是如何?
默认情况下,Razor会将页面模型向下传递给局部模型。 因此,假设_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.