[英]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.