You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC Razor 如何正确绑定嵌套Address对象实现表单提交后正常取值

问题根源

ASP.NET MVC 默认模型绑定器对嵌套复杂类型的字段有命名规则要求:字段的name属性必须遵循 父属性名.子属性名 的格式,你之前直接用AddressId作为字段名,绑定器无法识别该字段属于Customer下的CustomerAddress属性,自然无法完成赋值。

推荐解决方案

使用强类型的HtmlHelper扩展方法(如HiddenFor),框架会自动生成符合绑定规则的字段名,无需手动拼写,修改后Razor代码如下:

@model CustomerManagement.Model.ViewModels.Customers.Customer
@using (Html.BeginForm())
{
    @Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-control readOnlySchdCode", @readonly = "readonly" } })
    @* 嵌套属性绑定 *@
    @Html.HiddenFor(model => model.CustomerAddress.AddressId)
    @Html.HiddenFor(model => model.CustomerAddress.HouseName)
    @Html.HiddenFor(model => model.CustomerAddress.Location)
    <button type="submit" class="btn btn-primary">提交</button>
}

以上代码生成的隐藏字段实际结构如下,完全符合模型绑定要求:

<input type="hidden" name="CustomerAddress.AddressId" id="CustomerAddress_AddressId" value="你的地址ID值" />
<input type="hidden" name="CustomerAddress.HouseName" id="CustomerAddress_HouseName" value="你的门牌号值" />

可选解决方案(不推荐)

如果你坚持用非强类型的Hidden方法,手动指定字段名即可,但是注意属性名变更时编译器不会提示错误,容易引发线上问题:

@Html.Hidden("CustomerAddress.AddressId", Model.CustomerAddress.AddressId)
@Html.Hidden("CustomerAddress.HouseName", Model.CustomerAddress.HouseName)

注意事项

如果是新增客户场景,没有初始的地址数据,需要在返回视图的Action中初始化嵌套的CustomerAddress对象,否则页面渲染时会抛出空引用异常:

// 返回新增页面的Action示例
public ActionResult AddCustomer()
{
    var customer = new Customer
    {
        // 初始化嵌套对象,避免视图空引用
        CustomerAddress = new Address()
    };
    return View(customer);
}

修改后Controller即可正常读取嵌套属性:

public async Task<ActionResult> AddCustomer(Customer model)
{
    // 可正常获取嵌套属性值
    int addressId = model.CustomerAddress.AddressId;
    string houseName = model.CustomerAddress.HouseName;
    // 其余业务逻辑
    return RedirectToAction("Index");
}

内容的提问来源于stack exchange,提问作者vmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 10:12:04