0

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?

1 Answers1

0

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.

Community
  • 1
  • 1
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • So there are two Customer objects? One empty, one with form values as properties? It is just weird to me for just have a null Customer object doing nothing? –  Jan 30 '17 at 12:46
  • 1
    on the `GET` request, there's an object that contains a null `Customer` object, but still has metadata about the `Customer`. On postback, the ModelBinder will instantiate the `Customer` object and attempt to fill it in for your controller. – Jonesopolis Jan 30 '17 at 13:00
  • The html helper (`@Html.TextBoxFor(e => e.Customer.Name, ...`) is getting the metadata about the `Customer.Name` object to create labels for that input – Jonesopolis Jan 30 '17 at 13:01