Custom Model Binder

(ASP.NET MVC)


Hi,

  Model Binder feature in asp.net mvc allow us to create new model,validate/update the existing model.

  To implement model binder in asp.net mvc you have to implement IModelBinder interface. The IModelBinder interface has one method called BindModel. The signature of BindModel is given below

  public object BindModel(ControllerContext cntrlrContext,ModelBindingContext bindingContext)
  {
  }

  The BindModel method accepts two parameters. The first parameter is ControllerContext it has some  important properties like HttpContext,RequestContext and RouteData.
 
  The second parameter is of type ModelBindingContext. Some important properties of this parameter are  ModelMetadata, ModelName, ModelState,ModelType and PropertyMetadata.

public class EmployeeModelBinder: IModelBinder
    {
        public object BindModel(ControllerContext cntrlrContext,ModelBindingContext bindingContext)
        {
          
           ValueProviderResult valFirstName = bindingContext.ValueProvider.GetValue("FirstName");
            ValueProviderResult valLastName = bindingContext.ValueProvider.GetValue("LastName");
            ValueProviderResult valAge = bindingContext.ValueProvider.GetValue("Age");

            string firstName = valFirstName.AttemptedValue ?? null;
            string lastName = valLastName.AttemptedValue ?? null;
            int Age = valAge.AttemptedValue != null ? Convert.ToInt32(valAge.AttemptedValue) : 0;

            EmployeeModel empModel = new EmployeeModel();
            empModel.FirstName = firstName;
            empModel.LastName = lastName;
            empModel.Name = firstName + " " + lastName;
            empModel.Age = Age;
            return empModel;
           
        }
    }
   
   In the above code i created the class called EmployeeModelBinder which implements IModelBinder interface.I created the new employeemodel object in the bind model method. Then i populate the new employeemodel object properties and i return the newly created employeemodel object.

   I added this employeeModelBinder to the index action method as shown below

        [HttpPost]
        public ActionResult
Index([ModelBinder(typeof(EmployeeModelBinder))]EmployeeModel empobj)
        {
            ViewBag.Message = empobj.Name + "added successfully";
               return View();
        }

The index action method view code given below

EmployeeModel

 public class EmployeeModel
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
   }


index.cshtml


@{
    ViewBag.Title = "Home Page";
}

@model MVC4Tech.Controllers.EmployeeModel

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    <table>
        <thead>
            <tr>
                <th colspan="2">

                    <label>Add New Employee</label>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>

                    @Html.LabelFor(m=>m.FirstName)
                </td>
                <td>

                    @Html.TextBoxFor(m=>m.FirstName)
                </td>
            </tr>
            <tr>
                <td>

                    @Html.LabelFor(m => m.LastName)
                </td>
                <td>

                    @Html.TextBoxFor(m => m.LastName)
                </td>
            </tr>
            <tr>
                <td>

                    @Html.LabelFor(m => m.Age)
                </td>
                <td>

                    @Html.TextBoxFor(m => m.Age)
                </td>
            </tr>
            <tr>
                <td colspan="2">

                  <input type="submit" id="btn_addemployee" value="Add"/>
                </td>
              
            </tr>

        </tbody>
    </table>

}

@ViewBag.Message

Using this view iam getting the employee firstname, lastname and age from the user and send the populated employeemodel  to the server, in the server side using custom modelbinder iam populating the name property of employee model.


Ratings


Average Rating: 0.00 by 0 users
Giri Prasad
4/19/2014
4/19/2014
Download PDF
Download Project

Comments