【问题标题】:Passing model from view to controller using Html.RenderAction results in model being null使用 Html.RenderAction 将模型从视图传递到控制器导致模型为空
【发布时间】:2016-07-11 15:30:27
【问题描述】:

我有以下型号:

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);
}

那我有我的看法

索引.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

公司.cshtml

@model List<Company>

//Display model here

Admins.cshtml

@model List<Admin>

//Display model here

如您所见,我使用 Index.cshtml 来获取包含多个列表的对象。这是因为如果在列表中找不到任何项目,我需要隐藏这些操作。但是,当我使用@Html.RenderAction(...) 再次将它们传递给控制器​​时,当我期待一个列表时,我在控制器操作中得到 null。为什么?

【问题讨论】:

    标签: c# asp.net-mvc renderaction


    【解决方案1】:

    这样试试: 控制器:

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

    查看:

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

    【讨论】:

    • 太棒了!很高兴为您提供帮助!
    【解决方案2】:

    您必须将初始化的模型传递给控制器​​中的Index 视图。

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

    【讨论】:

    • 很抱歉打错了:)
    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多