Insert And Display Records With Model Binder Using ASP.NET MVC

Introduction

In this article, I am going to explain how to insert and display records with Model Binder using ASP.NET and Entity Data Model (DB First Approach).

Final Output

ASP.NET

Table

ASP.NET
  1. CREATE TABLE tblCustomer ( ID int IDENTITY (1, 1) PRIMARY KEY, FirstName nvarchar(50), LastName nvarchar(50), Age int, Address nvarchar(100) NULL ) INSERT [dbo].[tblCustomer] ([ID], [FirstName], [LastName], [Age], [Address])   
  2. VALUES  
  3.    (  
  4.       1, N'Bubai', N'Banerjee', 30, N'Kharghar'  
  5.    )  
  6.    INSERT [dbo].[tblCustomer] ([ID], [FirstName], [LastName], [Age], [Address])   
  7.    VALUES  
  8.       (  
  9.          2, N'Mala', N'Bose', 43, N'Belapur'  
  10.       )  
  11.       INSERT [dbo].[tblCustomer] ([ID], [FirstName], [LastName], [Age], [Address])   
  12.       VALUES  
  13.          (  
  14.             3, N'Satarup', N'Chatterjee', 28, N'Rampur Hat'  
  15.          )  
  16.          INSERT [dbo].[tblCustomer] ([ID], [FirstName], [LastName], [Age], [Address])   
  17.          VALUES  
  18.             (  
  19.                4, N'Soumo', N'Mukherjee', 69, N'Asansol'  
  20.             )  
Step 1 - Creating a MVC Project

Go to "File" >> “New" >> "Project...". Then, select "ASP.NET Web Application Template", provide the project a meaningful name of your choice, and click OK.

Click on MVC template and then click OK. In my case, the project name is “SampleProject”.

ASP.NET

ASP.NET

 Step 2 - Create Entity data model

Right click on “Models”>> “Add”, then “New Item” >> “Data” and select “ADO.NET entity data model”.

Enter Name >> click Add >> EF Designer from database >> Next. there, click on the "New Connection" button >> enter Server Name >> Enter Database Name>> click OK.

Select Table Name by clicking on checkbox >> Finish.

ASP.NET

Step 3

Build the project to get the Model details in Controller and Views. 

Step 4 - Create Controller

Right-click on Controller folder--- add --Controller --MVC5 controller Empty ---Click Add button -Change controller name (Don’t remove the Controller keyword, only change the name).

In my case, it is Home Controller.

Here, I used “Model Binder”. The Model binder is responsible to map View and Models. Most of the time, HTML designers are not aware of database field names. They use some common naming convention (like txtFullName) but database name is “FullName” only.

So, to work them smoothly, Model binder comes into the picture.

It uses IModelBinder interface which has methods like BindModel method. 

Step 5 - Create View

Right click on Controller Action method >> click on add View. View name will populate by default. If we want to change the name, we can do it. Select Template >> Modal Class >> Data Context class >> Add.

Here, I used pure HTML instead of HTML Helper class to communicate with the HTML designer smoothly.

  1. @ {  
  2.     if (TempData["message"] != null) { < script type = "text/javascript" > alert(@Html.Raw(Json.Encode(TempData["message"]))); < /script>  
  3.     }  
  4. }  

The above code is used to display the alert message after successfully saving record in the database.

@Html.Partial("_CustomerPartialView") is used to call the partial view. 

Step 6 - Create Partial View

Right click on Share folder -- Add --View--Enter View Name ----Select Template ----Check “Create as a partial View”

Here, I used the getJSON() method, to get JSON data using an AJAX HTTP GET request. Here it will call “GetCustomers” action method from Home controller.

ASP.NET

Complete Controller Code
  1. public class HomeController: Controller {  
  2.     AgainTestEntities se = new AgainTestEntities();  
  3.     public JsonResult GetCustomers() {  
  4.             var qry = se.tblCustomers.ToList();  
  5.             return Json(qry, JsonRequestBehavior.AllowGet);  
  6.         }  
  7.         [HttpGet]  
  8.     public ActionResult Index() {  
  9.             return View();  
  10.         }  
  11.         [HttpPost]  
  12.     public ActionResult Index([ModelBinder(typeof(CustomerBinder))] tblCustomer cust) {  
  13.         if (ModelState.IsValid) {  
  14.             se.tblCustomers.Add(cust);  
  15.             se.SaveChanges();  
  16.             TempData["message"] = "Record saved successfully";  
  17.         }  
  18.         return View();  
  19.     }  
  20.     public class CustomerBinder: IModelBinder {  
  21.         public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {  
  22.             HttpContextBase objContext = controllerContext.HttpContext;  
  23.             string custFirstName = objContext.Request.Form["txtFirstName"];  
  24.             string custLastName = objContext.Request.Form["txtLastName"];  
  25.             int custAge = Convert.ToInt32(objContext.Request.Form["txtAge"]);  
  26.             string custAddress = objContext.Request.Form["txtAddress"];  
  27.             tblCustomer objCustomer = new tblCustomer {  
  28.                 FirstName = custFirstName,  
  29.                     LastName = custLastName,  
  30.                     Age = custAge,  
  31.                     Address = custAddress  
  32.             };  
  33.             return objCustomer;  
  34.         }  
  35.     }  
  36. }  
Complete Index View
  1. @model SampleProject.Models.tblCustomer  
  2. @ {  
  3.     ViewBag.Title = "Index";  
  4. } < h2 > Customer Information < /h2>  
  5. @using(Html.BeginForm()) {  
  6.     @Html.AntiForgeryToken() < div class = "form-horizontal" > < hr / > @Html.ValidationSummary(true""new {  
  7.         @class = "text-danger"  
  8.     }) < div class = "form-group" > < label class = "control-label col-md-2" > FirstName < /label> < div class = "col-md-10" > < input type = "text"  
  9.     name = "txtFirstName"  
  10.     class = "form-control" / > < /div> < /div> < div class = "form-group" > < label class = "control-label col-md-2" > LastName < /label> < div class = "col-md-10" > < input type = "text"  
  11.     name = "txtLastName"  
  12.     class = "form-control" / > < /div> < /div> < div class = "form-group" > < label class = "control-label col-md-2" > Age < /label> < div class = "col-md-10" > < input type = "text"  
  13.     name = "txtAge"  
  14.     class = "form-control" / > < /div> < /div> < div class = "form-group" > < label class = "control-label col-md-2" > Address < /label> < div class = "col-md-10" > < input type = "text"  
  15.     name = "txtAddress"  
  16.     class = "form-control" / > < /div> < /div> < div class = "form-group" > < div class = "col-md-offset-2 col-md-10" > < input type = "submit"  
  17.     value = "Create"  
  18.     class = "btn btn-default" / > < /div> < /div> < div class = "form-group" > @Html.Partial("_CustomerPartialView") < /div> < /div>  
  19. }  
  20. @section Scripts {  
  21.     @Scripts.Render("~/bundles/jqueryval")  
  22. }  
  23. @ {  
  24.     if (TempData["message"] != null) { < script type = "text/javascript" > alert(@Html.Raw(Json.Encode(TempData["message"]))); < /script>  
  25.     }  
  26. }  

Complete Partial View Code

  1. @model SampleProject.Models.tblCustomer < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> < script type = "text/javascript" > $(document).ready(function() {  
  2.     var row;  
  3.     $.getJSON("/Home/GetCustomers"function(data) {  
  4.         $.each(data, function(i, CustData) {  
  5.             row = $('<tr/>');  
  6.             row.append("<td>" + CustData.FirstName + "</td>");  
  7.             row.append("<td>" + CustData.LastName + "</td>");  
  8.             row.append("<td>" + CustData.Age + "</td>");  
  9.             row.append("<td>" + CustData.Address + "</td>");  
  10.             $('#tblCust').append(row);  
  11.         });  
  12.     });  
  13. }); < /script> < table id = "tblCust"  
  14. class = "table table-bordered" > `  
  15.   
  16. <thead>  
  17.    <tr>  
  18.       <th>First Name</th>  
  19.       <th>Last Name</th>  
  20.       <th>Age</th>  
  21.       <th>Address</th>  
  22.    </tr>  
  23. </thead>  
  24.    <tbody></tbody>  
  25. </table>    
Step 7 - Run Application

We have done all the steps. Now, it’s time to run the application.

Press F5 to run this program and our output for the ASP.NET MVC application will be like as shown above. Once you have clicked on the "Create" button, the data will be saved into the database table and simultaneously, it will display on the page.

Summary

We have learned about inserting and displaying records with Model Binder using ASP.NET MVC, Entity Data Model, and SQL Server. Please refer to the attached code for better understanding. I hope this article is useful for all readers. If you encounter any problem, then feel free to contact me.


Similar Articles