【发布时间】:2021-09-24 01:39:28
【问题描述】:
我的 ASP.NET MVC 视图模型设计如下
public class Customer
{
public int CustomerId{ get; set; }
public string CustomerName{ get; set; }
public Address CustomerAddress {get;set;}
}
public class Address
{
public int AddressId{ get; set; }
public string HouseName{ get; set; }
public string Location{get;set;}
}
如何在 cshtml 页面中正确绑定地址对象,使其在表单提交后可用。
在cshtml页面中,我想绑定如下属性
@model CustomerManagement.Model.ViewModels.Customers.Customer
@using (Html.BeginForm())
{
@Html.EditorFor(model => model.CustomerName, new { htmlAttributes = new { @class = "form-
control readOnlySchdCode", @readonly = "readonly" } })
@Html.Hidden("AddressId", Model.Address.AddressId)
@Html.Hidden("HouseName", Model.Address.HouseName)
}
在控制器表单中提交如下所示
public async Task<ActionResult> AddCustomer(Customer model)
{
//How can i access Address properties eg:model.CustomerAddress.AddressId??
}
任何人都可以分享一个示例代码,说明如何使用 razor 模板在 cshtml 中正确绑定上述视图模型,以及在表单提交时如何在 Action 方法中正确检索属性。
【问题讨论】:
-
您是否尝试过使用 Helper Model 表示 Customer 和 Address 的模型组合?
-
@ashhadullah..我不熟悉..你能解释一下
-
您好,请问还有什么可以帮助您的吗?
标签: c# .net asp.net-mvc asp.net-core model-binding