使用EditorFor时丢失帖子上的数据

时间:2011-04-13 19:20:11

标签: asp.net-mvc-3 viewmodel

问题:

当我提交表单时,我将丢失输入到地址编辑模板中的任何信息。

我有以下型号:

public class MoveRecord
{
    public Address StartPoint { get; set; }
    public Address EndPoint { get; set; }
}

地址定义为:

public class Address
{
    public String City { get; set;}
    public String State { get; set; }
    public String Line1{ get; set; }
    public String PostalCode { get; set; }
}

这是我的行动方法:

[HttpPost]
public ActionResult Edit(MoveRecord model)
{
    if (ModelState.IsValid)
    {
        //Save info
    }

    return View(model);
}

我的编辑视图使用:

using (Html.BeginForm("Edit", "Move", FormMethod.Post))
{
    @Html.EditorFor(m => m.StartPoint);
    @Html.EditorFor(m => m.EndPoint);
    <input type="submit" value="Save" />
}

我的编辑模板是:

<table class="form address">
    <tbody>
        <tr>
            <th style="width: 200px;">
                @Html.LabelFor(m => m.Line1):
            </th>
            <td>
                @Html.TextBoxFor(m => m.Line1, new { style = "width: 300px;" })
            </td>
        </tr>
        <tr id="zip">
            <th>
                @Html.LabelFor(m => m.PostalCode):
            </th>
            <td>
                @Html.TextBoxFor(m => m.PostalCode, new { style = "width: 150px;" })
            </td>
        </tr>
        <tr id="city">
            <th>
                @Html.LabelFor(m => m.City):
            </th>
            <td>
                @Html.TextBoxFor(m => m.City, new { style = "width: 150px;" })
            </td>
        </tr>
        <tr id="state">
            <th>
                @Html.LabelFor(m => m.StateProvince):
            </th>
            <td> 
               @Html.TextBoxFor(m => m.StateProvince, new { style = "width: 150px;" })
            </td>
        </tr>
    </tbody>
</table>

一切都呈现得很好,但是当我提交表单时,我在action方法中获得的模型不包含输入到地址字段中的任何信息。如果我将所有内容都移动到相同的视图中,那么它的工作正常,但我希望能够使用编辑器模板来保持我的视图易于阅读。 如何将编辑器模板中的数据正确绑定到模型?

编辑:发布我的操作方法

1 个答案:

答案 0 :(得分:0)

您提交表单的操作必须如下所示:

[HttpPost]
public ActionResult Edit(MoveRecord model)
{
    // model.StartPoint and model.EndPoint should be correctly bound here.
    ...
}

或者,如果您尝试直接绑定到两个地址,则需要设置正确的前缀:

[HttpPost]
public ActionResult Edit(
    [Bind(Prefix = "StartPoint")] Address start, 
    [Bind(Prefix = "EndPoint")] Address end
)
{
    ...
}