2014-09-22 70 views
2

我學習ASP.NET MVC的最後幾天。當我在「主」視圖中使用兩個或更多模型時,我遇到問題。ASP.NET MVC中的多個模型(PartialView方法)

型號之一:

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.InvalidOperationException」類型的異常出現在 System.Web.Mvc.dll程序,但在用戶代碼中沒有處理

附加信息:傳遞到字典的模型產品類型 「系統的 。 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 ..但是如何?

+1

請將您的完整查看代碼 – krisdyson 2014-09-22 11:23:31

+0

您正在調用哪個操作?從PersonController索引或EmployerController索引? – 2016-11-23 04:22:09

回答

0

默認情況下,Razor會將頁面模型傳遞給部分。因此,假設_emp.cshtml視圖具有的IEnumerable<Employee>而非IEnumerable<Person>那麼你可以使用重載@Html.Partial覆蓋模型

@Html.Partial("~/Views/Employer/_emp.cshtml", Model.Cast<Employee>()) 
0

試試這個(不要有一臺機器上運行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. 
相關問題