与 ASP.NET 中的 html 助手混淆

confused with html helper in ASP.NET

我有一个视图模型class

public class NewCustomerViewModel
{
   public IEnumerable<MembershipType> MembershipType { get; set; }
   public Customer Customer { get; set; }
}

我有一个带有 New() 操作方法的 Customers 控制器:

public ActionResult New()
{
    var membershipTypes = _context.MembershipTypes.ToList();
    var viewModel = new NewCustomerViewModel
    {
        MembershipType = membershipTypes
    };

    return View(viewModel);
}

观点是:

@using (Html.BeginForm("Create", "Customers"))
{ 
    <div class="form-group">
        @Html.LabelFor(e => e.Customer.Name)
        @Html.TextBoxFor(e => e.Customer.Name, new { @class = "form-control" })
    </div>
    <div class="form-group">
        @Html.LabelFor(e => e.Customer.Birthdate)
        @Html.TextBoxFor(e => e.Customer.Birthdate, new { @class = "form-control" })
    </div>
    <div class="checkbox">
        <label>
           @Html.CheckBoxFor(e => e.Customer.IsSubscribedToNewsletter, new { @class = "checkbox" }) Subscribed To Newsletter?
        </label>
    </div>

例如,这是做什么用的?

@Html.TextBoxFor(e => e.Customer.Name, ...)

目前我们只有一个空的 Customer 实例,我们正在尝试获取名称?

我刚才this same question

虽然您从未实例化 Customer,但对象已定义且引擎能够为其构建视图。

在回发时,ModelBinder 将实例化一个新的 Customer 并尝试从您的表单值中填充它。网络是无状态的,因此无论您在构建表单时发送 pre-populated Customer 对象还是空对象都没有关系,在回发时 ASP.NET 只能根据其中的内容构建它表格。