articles

Home / DeveloperSection / Articles / Model Binding in MVC

Model Binding in MVC

Anonymous User 1616 22-Dec-2018

Hi Friends,

Here, Today I'm providing a brief explanation for model binding in MVC. And I'll also describe that why it is important. Then let's start...

As we know that Model is the most important part of MVC technology. The MVC model binding allows you to map HTTP request data with a model. This is the process of creating .NET objects using the data sent by the browser in an HTTP request. An ASP.NET Web Forms developers who are new to ASP.Net MVC are mostly confused how the values from View get converted to the Model class when it reaches the ActionMethod of the Controller class, so this conversion is done by the Model Binder. That is the Model binding is a mechanism ASP.NET MVC uses to create parameter objects defined in controller action methods. Here parameters can be of any type, from simple to complex ones. The MVC solves these problems by abstracting binding away so developers don't have to keep rewriting a slightly different version of that same code in every app. It is a great feature of MVC because mapping incoming data to a counterpart is an often repeated scenario, regardless of size or complexity of the data. The Model binding is a well-designed bridge (pattern) between the HTTP request and the C# ActionMethods. This makes, it’s easy for developers to work with data on forms (views) because POST and GET is automatically transferred into a data model you specify. The MVC uses default binders to complete this behind the scene.

Model Binding in MVC

Into the ASP.NET MVC, we can create our Models using Entity Framework, ADO.NET Code or any other data access techniques. As long as developing the Model layer, we declare Plain Old CLR Objects (POCO). Supposing we use EntityFramework, then the application provides POCO objects which we can use as entities.

IModelBinderProvider interface - Its interface contains methods that enable dynamic implementation of model binding for classes which implement the IModelBinder interface. It is used to manage the custom binder for the type of data posted by the end-user in views.

IModelBinder interface - It defines methods that are required for a Model Binder, like the BindModel method. That method is responsible for binding a model to some values using ControllerContext and BindingContext.

Step-1). When we add an entity framework to our project for adding a database and their tables then a model class automatic generated there. Like below code.

namespace MvcApplication3.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    public partial class UserProfile
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string ContactNo { get; set; }
        public string Address { get; set; }
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> Dob { get; set; }
        public Nullable<long> CreatedBy { get; set; }
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> CreatedOn { get; set; }
        public Nullable<long> ModifiedBy { get; set; }
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> ModifiedOn { get; set; }
    }
}

Model Binding in MVC

in simple word, it is a structural image of our table's columns.

Step-2). Then add a controller file in controller folder for Action execution by  Action Method. Like this..

using MvcApplication3.Models;
using MvcApplication3.Models.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication3.Controllers
{
    public class HomeController : Controller
    {
        private AllRepository interfaceobj;
        public HomeController()
        {
            interfaceobj = new AllRepository(new DataContext());
        }
        public ActionResult Index()
        {
            List<UserProfile> listbook = new List<UserProfile>();
            var data = from m in interfaceobj.GetUserProfiles() select m;
            return View(data);
        }
        public ActionResult Details(int UserId)
        {
            UserProfile b = interfaceobj.GetUserBYID(UserId);
            return View(b);         }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(UserProfile user)         {
            try
            {
                interfaceobj.InsertUser(user);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View();
            }
        }
        public ActionResult Edit(int UserId)
        {
            UserProfile B = interfaceobj.GetUserBYID(UserId);
            return View(B);
        }
        [HttpPost]
        public ActionResult Edit(int UserId, UserProfile user)
        {
            try
            {
                interfaceobj.UpdateUser(user);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        [HttpPost]
        public ActionResult Delete(int UserId)
        {
            try
            {                 interfaceobj.DeleteUser(UserId);
                interfaceobj.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

Model Binding in MVC

Step-3).  After creating the controller and action methods then add their UI page as depends upon their rolls like Create, Edit, Detail, Delete etc. Here UI page is known as View. For creating a view  Go and right-click on an ActionMethod's area and select "Add a view" 

Model Binding in MVC

Model Binding in MVC

Model Binding in MVC

Note:- If when you'll create the controller then after the whole project needs to Build/Rebuild for activation all dll or registries files. Then create their UI.

Thank You for reading this article !!! If any suggestion Please comment me by comment box.


Updated 17-Oct-2019
I am a content writter !

Leave Comment

Comments

Liked By