2016-07-11 95 views
0

我有以下型號:傳遞模型使用模型Html.RenderAction結果控制器被空

public class Foo 
{ 
    public List<Employee> Employees{ get; set; } 
    public List<Company> Companies{ get; set; } 
    public List<Admin> Admins{ get; set; } 
} 

然後,我有我的控制器操作:

public ActionResult Index() 
{ 
    Foo model = GetFooFromSomewhere(); 
    return PartialView("Index", model); 
} 

public ActionResult Employees(List<Employee> model) 
{ 
    return PartialView("Employees", model); 
} 

public ActionResult Companies(List<Company> model) 
{ 
    return PartialView("Companies", model); 
} 

public ActionResult Admins(List<Admin> model) 
{ 
    return PartialView("Admins", model); 
} 

然後,我有我的看法

Index.cshml:

@model Foo 
@if(Model.Employees.Count > 0) 
{ 
    @{Html.RenderAction("Employees", "Config", Model.Employees);} 
} 
@if(Model.Companies.Count > 0) 
{ 
    @{Html.RenderAction("Companies", "Config", Model.Companies);} 
} 
@if(Model.Admins.Count > 0) 
{ 
    @{Html.RenderAction("Admins", "Config", Model.Admins);} 
} 

Employees.cshtml:

@model List<Employee> 

//Display model here 

Companies.cshtml

@model List<Company> 

//Display model here 

Admins.cshtml

@model List<Admin> 

//Display model here 

正如你所看到的,我用Index.cshtml獲得中包含多個對象名單。這是因爲如果在列表中找不到任何項目,我需要隱藏這些操作。但是,當我使用@ Html.RenderAction(...)再次將它們傳遞給控制器​​時,我期待列表中的控制器操作時會得到null。爲什麼?

回答

2

嘗試這種方式: 控制器:

public ActionResult Admins(List<Admin> m) 
{ 
    return PartialView("Admins", m); 
} 

查看:

@{Html.RenderAction("Admins", "Config", new { m = Model.Admins });} 
+0

由於這是問題 – LeonidasFett

+0

太棒了!很高興幫助你! – Luca

1

您必須將模型初始化爲控制器中的Index視圖。

public ActionResult Index() 
{ 
    Foo model = GetFooFromSomewhere(); 
    return PartialView("Index", model); 
} 
+0

對不起,這是一個錯字:) – LeonidasFett

相關問題