asp.net-mvc - MVC 4 列表模型向 Controller 返回 null

标签 asp.net-mvc list asp.net-mvc-4 null

这是我的代码:

模型

public class InformationsModel
{
    public List<InformationModel> infos { get; set; }

    public InformationsModel()
    {
    }
}

public class InformationModel
{
    public InformationModel() {

    }

    public string Name { get; set; }
    public string Value { get; set; }
    public string Group { get; set; }
    public string Type { get; set; }
    public bool Avaiable { get; set; }    
}

查看

@model InterfaceWeb.Models.InformationsModel


@using (Html.BeginForm("UpdateInformations", "Main", FormMethod.Post, new { @id = "frmInformations" }))
{    
    @Html.EditorFor(x => x.infos)                
}

模板

@model InterfaceWeb.Models.Information.InformationModel

<div class="infoMain">
    <div class="colunas">
        @Html.TextBoxFor(x => x.Name, new { style = "width:250px;" })
    </div>
    <div class="colunas">
            @Html.TextBoxFor(x => x.Value, new { style = "width:120px;" })
    </div>
    <div class="colunas">
        @Html.TextBoxFor(x => x.Group, new { style = "width:120px;" })
    </div>
    <div class="colunas">
        @Html.TextBoxFor(x => x.Type, new { style = "width:150px;" })
    </div>
    <div class="colunas">
        @Html.CheckBoxFor(x => x.Avaiable, new { style = "width:10px; margin-left:20px;" })
    </div>
</div>

Controller

[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{                

}

当我到达 Controller 时,我的模型是空的,我不明白为什么。

我尝试更改模板、 View 、初始化列表之后、之前,但没有任何效果..

感谢您的帮助! =)

最佳答案

由于模型前缀的工作方式,您遇到了此问题。具体来说,问题就在这里:

[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{             

}

如果您查看模板生成的 HTML,您会发现它的内容如下:

<input id="infos_0__Name" name="infos[0].Name" type="text" value="" />

在这种情况下,需要了解的重要一点是 infos 是与 InformationsModel.infos 属性值关联的前缀。通过在 Controller infos 中命名参数,您将摆脱模型绑定(bind)器。您只需重命名它即可获取值,如下所示:

[HttpPost]
public ActionResult UpdateInformations(InformationsModel model)
{             

}

顺便说一句,我建议将 InformationModel 重命名为更合适的名称,例如 PersonEmployee 或任何您想要的名称造型。遵循您想要做的事情有点困难,只是因为类名称几乎相同,并且名称并没有真正传达它们的意图。

关于asp.net-mvc - MVC 4 列表模型向 Controller 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073804/

相关文章:

javascript - ASP.NET如何在不刷新页面的情况下更新数据库

c# - 当我尝试展开模型属性时,为什么 Visual Studio 2013 调试器关闭时没有错误?

javascript - 如何从 JS 将参数发送到我的 Controller ASP?

python-3.x - 如何将两个嵌套列表附加到Python中的单个嵌套列表中

html - 如何使我的文本框只包含数字?

azure - 为什么指向 Azure 共享缓存的 Web outputCache 配置部分会减慢每个请求的速度?

asp.net - IIS 7 应用程序池工作进程生命和 session 生命

java - java中访问列表索引时出现索引越界异常

python - 如果键存在则附加到字典中的值/将值转换为列表然后附加

c# - 返回特定列大小写时