Search code examples
c#asp.nethtml-helper

confused with html helper in ASP.NET


I have a view model class

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

and I have a Customers controller with New() action method :

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

    return View(viewModel);
}

the view is :

@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>

For example, what's this for?

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

we just have an empty Customer instance at the moment and we are trying to get the name?


Solution

  • I had this same question a while ago.

    Though you are never instantiating Customer, the object is defined and the engine is able to build your view for it.

    On postback, the ModelBinder will instantiate a new Customer and try to populate it back up from your form values. The web is stateless, so it doesn't matter if you sent in a pre-populated Customer object or an empty one when building the form, on postback ASP.NET can only construct it from what's in the form.