ASP.Net MVC Scribblings
  • Introduction
  • Introduction
    • My ASP.net MVC Scribblings
    • Test
  • ASP.net MVC
    • Routing
    • Passing Data in MVC
      • ViewData and ViewBag
      • ViewData / ViewBag
      • TempData
      • Session Variables
    • ModelBinder
    • Advantages of MVC over WebForms
    • Data Annotation
    • RAZOR
    • ActionName decorator for overloaded Controller actions
    • Security
      • CSRF
      • XSS
    • Shared Layout page
    • Custom Claims-based Windows Authentication in ASP.net MVC 5
Powered by GitBook
On this page

Was this helpful?

  1. ASP.net MVC

ModelBinder

In a Controller Action, ModelBinder maps the incoming request data to the to the properties of the Model object that is passed as parameter to the action method.

If the input HTML element names in the View form, that user submits, match with the Model property names, then MVC would automatically map those elements' to the model properties matching with the element names and create an instance of the Model using the values/data of those elements.

public class CustomerController: Controller {

    public ActionResult EnterCustomerDetails(){
        render View("EnterCustomerDetails");
    }

    /*
    if in the EnterCustomerDetails view , we have a HTML form with action="SubmitCustomerDetails" (below Action) and the names of the input fields in the form match exactly with the Customer model, then in the below method, MVC would automatically match the passed `customer` parameter's properties to the input field's data matching with the property name. Thus data in a field name 'name' would be assigned to customer.name property
    */


    public ActionResult SubmitCustomerDetails(Customer customer) {
        return View("ShowCustomerDetails", customer);
    }
}

In case the names of the HTML input fields name don't exactly match with the property names of the model, a custom ModelBinder class can be created and can be used to map the input fields values with the model object's properties.

PreviousSession VariablesNextAdvantages of MVC over WebForms

Last updated 5 years ago

Was this helpful?