MVC 4 List Model将null返回给控制器

时间:2013-09-29 02:29:54

标签: 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>

控制器

[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{                

}

当我到达控制器时,我的模型是空的,我无法找出原因。

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

Thx任何帮助! =)

2 个答案:

答案 0 :(得分:2)

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

[HttpPost]
public ActionResult UpdateInformations(InformationsModel infos)
{             

}

如果您查看模板生成的HTML,您会发现它与此类似:

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

在这种情况下,重要的是要知道infos是与InformationsModel.infos属性的值相关联的前缀。通过在控制器infos中命名参数,您将丢弃模型绑定器。您只需重命名它以获取值,如下所示:

[HttpPost]
public ActionResult UpdateInformations(InformationsModel model)
{             

}

顺便说一句,我建议将InformationModel重命名为更合适的内容,例如PersonEmployee或其他正在建模的内容。你想要做的事情有点困难,因为班级名称几乎完全相同,名字并没有真正传达他们的意图。

答案 1 :(得分:0)

你的问题可能在于命名事物:)

更改您的控制器:

[HttpPost] public ActionResult UpdateInformations(InformationsModel infos) { }

使用:

[HttpPost] public ActionResult UpdateInformations(InformationsModel model) { }

或者在您的模型更改列表中将“infos”命名为其他内容。

实施例:

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

    public InformationsModel()
    {
    }
}

改变:

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

    public InformationsModel()
    {
    }
}