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
Table
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])
VALUES
(1, N'Bubai', N'Banerjee', 30, N'Kharghar'),
(2, N'Mala', N'Bose', 43, N'Belapur'),
(3, N'Satarup', N'Chatterjee', 28, N'Rampur Hat'),
(4, N'Soumo', N'Mukherjee', 69, N'Asansol')
Step 1. Creating an MVC Project
Go to "File" >> “New" >> "Project...". Then, select "ASP.NET Web Application Template", provide the project with a meaningful name of your choice, and click OK.
Click on the MVC template and then click OK. In my case, the project name is “SampleProject”.
Step 2. Create an 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.
Step 3. Build the project to get the Model details in the 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 the Home Controller.
Here, I used “Model Binder”. The Model binder is responsible for mapping 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 the database name is “FullName” only.
So, to work them smoothly, the Model binder comes into the picture.
It uses the IModelBinder interface which has methods like the BindModel method.
Step 5. Create a View
Right-click on Controller Action method >> click on add View. The 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 the HTML Helper class to communicate with the HTML designer smoothly.
@{
if (TempData["message"] != null) {
<script type="text/javascript">
alert(@Html.Raw(Json.Encode(TempData["message"])));
</script>
}
}
The above code is used to display the alert message after successfully saving the record in the database.
@Html.Partial("_CustomerPartialView") is used to call the partial view.
Step 6. Create a 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 the “GetCustomers” action method from the Home controller.
Complete Controller Code
public class HomeController : Controller
{
AgainTestEntities se = new AgainTestEntities();
public JsonResult GetCustomers()
{
var qry = se.tblCustomers.ToList();
return Json(qry, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index([ModelBinder(typeof(CustomerBinder))] tblCustomer cust)
{
if (ModelState.IsValid)
{
se.tblCustomers.Add(cust);
se.SaveChanges();
TempData["message"] = "Record saved successfully";
}
return View();
}
public class CustomerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpContextBase objContext = controllerContext.HttpContext;
string custFirstName = objContext.Request.Form["txtFirstName"];
string custLastName = objContext.Request.Form["txtLastName"];
int custAge = Convert.ToInt32(objContext.Request.Form["txtAge"]);
string custAddress = objContext.Request.Form["txtAddress"];
tblCustomer objCustomer = new tblCustomer
{
FirstName = custFirstName,
LastName = custLastName,
Age = custAge,
Address = custAddress
};
return objCustomer;
}
}
}
Complete Index View
@model SampleProject.Models.tblCustomer
@{
ViewBag.Title = "Index";
}
<h2>Customer Information</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class = "form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class = "form-group">
<label class = "control-label col-md-2"> FirstName </label>
<div class = "col-md-10">
<input type = "text" name = "txtFirstName" 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" name = "txtLastName" 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" name = "txtAge" 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" name = "txtAddress" class = "form-control" />
</div>
</div>
<div class = "form-group">
<div class = "col-md-offset-2 col-md-10">
<input type = "submit" value = "Create" class = "btn btn-default" />
</div>
</div>
<div class = "form-group">
@Html.Partial("_CustomerPartialView")
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@{
if (TempData["message"] != null) {
<script type = "text/javascript">
alert(@Html.Raw(Json.Encode(TempData["message"])));
</script>
}
}
Complete Partial View Code
@model SampleProject.Models.tblCustomer
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var row;
$.getJSON("/Home/GetCustomers", function(data) {
$.each(data, function(i, CustData) {
row = $('<tr/>');
row.append("<td>" + CustData.FirstName + "</td>");
row.append("<td>" + CustData.LastName + "</td>");
row.append("<td>" + CustData.Age + "</td>");
row.append("<td>" + CustData.Address + "</td>");
$('#tblCust').append(row);
});
});
});
</script>
<table id="tblCust" class="table table-bordered">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Address</th>
</tr>
</thead>
<tbody></tbody>
</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 problems, then feel free to contact me.