部分视图模型的值在提交时为null

时间:2012-12-18 09:23:12

标签: c# asp.net-mvc

我无法将部分视图中的值成功发布到我的操作中 - 所有属性都为null。

部分视图模型:

public class AddressViewModel
{
   public string ClientNumber { get; set; }
   public string Line1 { get; set; }
   public string Line2 { get; set; }
   public string Line3 { get; set; }
   public string Suburb { get; set; }
   public string PostalCode { get; set; }
}

部分视图:

@model Models.AddressViewModel
@{
    Layout = null;
}

@using (Html.BeginForm("UseAddress", "Home"))
    { 
<div>
    <table>
        <tr>
            <td>
                <div class="display-label">
                    @Html.DisplayNameFor(model => model.Line1)
                </div>
            </td>
            <td>
                <div class="display-field">
                    @Html.DisplayFor(model => model.Line1)
                </div>
            </td> 
........
        </tr>
    </table>

    <input type="submit" name="UseAddress" id="submitbutton" value="Use Address" />

</div>
}

动作:

[HttpPost]
[Authorize]
public ActionResult UseAddress(AddressViewModel model)
{
    return RedirectToAction("Index", "Home");
}

通过选择下拉列表在页面上呈现部分视图,如下所示:

<script type="text/javascript">
    $(function () {
        $('#AddressTypeDropdownList').change(function () {          
            var url = $(this).data('url');          
            $('#Address').load(url);
        });
    });
</script>

    @Html.DropDownListFor(
    x => x.SelectedAddressTypeId,
    new SelectList(Model.AddressTypes, "Value", "Text"),
    "-- Select Address Type --",
         new
         {
             id = "AddressTypeDropdownList",
             data_url = Url.Action("_Address", "Home")
         }
    )
    <div id="Address"></div>          


    public ActionResult _Address()
    {        
        AddressViewModel addressViewModel = new AddressViewModel {
            ClientNumber = "test"          
        };         

        return PartialView(addressViewModel);
    }

当我点击提交按钮时,我希望UseAddress方法具有model.ClientNumber == "test",但它是null ...有什么明显的我做错了吗?

1 个答案:

答案 0 :(得分:3)

DisplayFor不会为该字段创建输入,因此不会发布。你需要添加

@Html.HiddenFor(model => model.Line1)
....

发布值。