Basic model binding in MVC - beginners

/
0 Comments

ModelBinding is the mechanism ASP.NET MVC uses to create strongly-typed objects (or fill primitive-type parameters) from the input stream (usually an HTTP request). The Model-Binder is then responsible to fill that person parameter for you.

Model Binding allows you to map and bind the HTTP request data with a model. If you want to work with the form data, Model Binding makes it easier because the requested data is submitted automatically into a data model that we specify. The Default Binder is used to do this. i explained the modelbinding with example,

Create New Project

created the project with name MvcModelBinding with basic template

Create the controller

created the new controller with name User

Create a new view

created the new view with name Userinfo under views->User Folder

Create a new model

code

Code Snippet
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5.  
  6. namespace MvcModelBinding.Models
  7. {
  8.     public class UserInfoModel     {
  9.         public string Id { get; set; }
  10.         public string Name { get; set; }
  11.         public int Age { get; set; }
  12.         public string City { get; set; }
  13.         public string Country { get; set; }
  14.  
  15.     }
  16. }

created the new model with name UserInfoModel under model folder.it is having Name,Age,City and Country properties.

Add input fields into view

Code Snippet
  1. @{
  2.     ViewBag.Title = "UserInfo";
  3. }
  4. <h2>UserInfo</h2>
  5.     <div>
  6.             @{Html.BeginForm("UserInfo", "User");
  7.                 <table>
  8.                     <tr>
  9.                         <td>First Name : </td>
  10.                         <td>@Html.TextBox("fname")</td>
  11.                     </tr>
  12.                     <tr>
  13.                         <td>Middle Name : </td>
  14.                         <td>@Html.TextBox("midname")</td>
  15.                     </tr>
  16.                     <tr>
  17.                         <td>lastName :</td>
  18.                         <td> @Html.TextBox("lname")</td>
  19.                     </tr>
  20.                     <tr>
  21.                         <td>Age:</td>
  22.                         <td> @Html.TextBox("age") </td>
  23.                     </tr>
  24.  
  25.                      <tr>
  26.                         <td>Place:</td>
  27.                         <td> @Html.TextBox("place") </td>
  28.                     </tr>
  29.                      <tr>
  30.                         <td>Nationality:</td>
  31.                         <td> @Html.TextBox("nationality") </td>
  32.                     </tr>
  33.                     <tr>
  34.                         <td></td>
  35.                         <td>
  36.                             <input type="submit" name="Save" value="submit" />
  37.                         </td>
  38.                     </tr>
  39.                 </table>
  40.             }
  41.     </div>

created the textbox inputs for first name,middle name,last name,place,nationality and age in newly created view.

Create new UserModelBinding class for ModelBinding

Code Snippet
  1. using MvcModelBinding.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Http.Controllers;
  7. using System.Web.Http.ModelBinding;
  8. using System.Web.Mvc;
  9.  
  10. namespace MvcModelBinding.Data
  11. {
  12.     public class UserModelBinding : System.Web.Mvc.IModelBinder
  13.     {
  14.         public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
  15.         {
  16.             var request = controllerContext.HttpContext.Request;
  17.             var UserInfo = new UserInfoModel();
  18.             UserInfo.Name = string.Format("{0}{1}{2}", request.Form.Get("fname"), request.Form.Get("midname"), request.Form.Get("lname"));
  19.             UserInfo.Country = request.Form.Get("nationality");
  20.             UserInfo.City = request.Form.Get("place");
  21.             UserInfo.Age = Convert.ToInt32(request.Form.Get("age"));
  22.             return UserInfo;
  23.         }        
  24.     }
  25. }

created the new UserModelBinding class for model binding the inputs such as first name,middle name,last name,place,nationality and age from view.

Create action methods

Code Snippet
  1. public ActionResult UserInfo()
  2.         {
  3.             return View();
  4.         }
  5.         
  6.         [HttpPost]
  7.         public ActionResult UserInfo([ModelBinder(typeof(UserModelBinding))] UserInfoModel data)
  8.         {
  9.             // do database operations or any
  10.  
  11.             return View();
  12.         }

created two action methods for userinfo view and one defined as post with model binder used for convert the input values into UserInfoModel.

Modify the default action method

Code Snippet
  1. public static void RegisterRoutes(RouteCollection routes)
  2.         {
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  4.  
  5.             routes.MapRoute(
  6.                 name: "Default",
  7.                 url: "{controller}/{action}/{id}",
  8.                 defaults: new { controller = "User", action = "UserInfo", id = UrlParameter.Optional }
  9.             );
  10.         }

modified the action and controller names for default in RouteConfig.cs file .

Run the project

just filled the informations for input fields

While debug the action method

The values are converted/assigned into UserInfoModel by ModelBinding



You may also like

No comments:

Powered by Blogger.