So in this article we will learn how to post whole data of strongly typed Html.BeginForm view into database without whole postback using jQuery json with the help of Ajax request instead of Ajax.BeginForm
So, let's demonstrate it by using a simple MVC application.
Step 1: Create an MVC Application.
- As shown in the preceding screenshot, click on Empty template and check MVC option, then click OK. This will create an empty MVC web application.
Step 2 : Add The Reference of Dapper ORM into Project.
Now next step is to add the reference of Dapper ORM into our created MVC Project. Here are the steps:
- Right click on Solution ,find Manage NuGet Package manager and click on it.
- After as shown into the image and type in search box "dapper".
- Select Dapper as shown into the image .
- Choose version of dapper library and click on install button.
After installing the Dapper library, it will be added into the References of our solution explorer of MVC application such as:
If wants to learn how to install correct Dapper library , watch my video tutorial using following link,
Now let us add the MVC 5 controller as in the following screenshot:
After clicking on
Add button it will show the window. specify the
Controller name as Home with suffix
Controller:
Now before creating the views let us create the table named
Employee in the database according to our model fields to store the details:
Create stored procedure to insert records
- Create procedure [dbo].[AddEmp]
- (
- @Name varchar (50),
- @City varchar (50),
- @Address varchar (50)
- )
- as
- begin
- Insert into Employee values(@Name,@City,@Address)
- End
I hope you have created the same table structure as shown above. Now create the stored procedures to insert the employee details as in the following code snippet:
Now run the above script in sql editor it will generates the stored procedure to insert details into database .
Step 6: Create Repository class.
Now create Repository folder and Add EmpRepository.cs class for database related operations, Now create method in EmpRepository.cs to insert the data into database using stored procedure with the help of dapper as in the following code snippet:
- using Dapper;
- using System.Data;
- using System.Configuration;
- using System.Data.SqlClient;
- using PostStronglyTypedDataInMVC.Models;
-
- namespace PostStronglyTypedDataInMVC.Repository
- {
- public class EmpRepository
- {
- SqlConnection con;
-
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
- con = new SqlConnection(constr);
- }
-
- public void AddEmpDetails(EmpModel emp)
- {
-
- DynamicParameters ObjParm = new DynamicParameters();
- ObjParm.Add("@Name", emp.Name);
- ObjParm.Add("@City", emp.City);
- ObjParm.Add("@Address", emp.Address);
- connection();
- con.Open();
- con.Execute("AddEmp", ObjParm,commandType:CommandType.StoredProcedure);
- con.Close();
-
-
- }
- }
- }
Note
- In the above code we are manually opening and closing connection, however you can directly pass the connection string to the dapper without opening it. Dapper will automatically handle it.
Step 7: Create Method into the HomeController.cs file.
Now open the HomeController.cs and create the following action methods:
- using PostStronglyTypedDataInMVC.Models;
- using System.Web.Mvc;
- using PostStronglyTypedDataInMVC.Repository;
- namespace PostStronglyTypedDataInMVC.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Employee()
- {
- return View();
- }
- [HttpPost]
- public JsonResult Employee(EmpModel obj)
- {
- EmpRepository ObjRepo = new EmpRepository();
- ObjRepo.AddEmpDetails(obj);
-
- return Json("Success",JsonRequestBehavior.AllowGet);
- }
- }
- }
Step 8 : Creating strongly typed view named Employee using EmpModel class .
Right click on View folder of created application and choose add view , select EmpModel class and create scaffolding template as,
Right click on View folder of created MVC application project and add empty view named Employee.cshtml.
Step 9: Create jQuery Post method
Now open the Employee.cshtml view and create the following jQuery Post method to call controller.
- <script type="text/javascript">
- $(document).ready(function () {
- $("#EmpForm").submit(function (e) {
- e.preventDefault();
- if ($(this).valid()) {
- $.ajax({
- type: "POST",
- url: $(this).attr('action'),
- data: $(this).serialize(),
- success: function (res)
- {
- alert("Records added Successfully.");
- }
- });
- }
- });
-
- })
-
- </script>
Note
- To work with jQuery we need to reference jQuery library .You can use the following CDN jQuery library from any provider such as Microsoft,Google or jQuery .
To use above jQuery library you need an active internet connection, if you don't have then you can use the following offline jQuery library as well:
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
Now after adding the required api or jQuery reference and code the entire Employee.cshtml view will be look like as follows Employee.cshtml,
- @model PostStronglyTypedDataInMVC.Models.EmpModel
-
- @{
- ViewBag.Title = "www.compilemode.com";
- }
- <script src="~/Scripts/jquery-2.2.3.min.js"></script>
- <script src="~/Scripts/jquery.validate.min.js"></script>
- <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $("#EmpForm").submit(function (e) {
- e.preventDefault();
- if ($(this).valid()) {
- $.ajax({
- type: "POST",
- url: $(this).attr('action'),
- data: $(this).serialize(),
- success: function (res)
- {
- alert("Records added Successfully.");
- }
- });
- }
- });
-
- })
-
- </script>
-
- @using (Html.BeginForm("Employee","Home",FormMethod.Post,new {id="EmpForm" }))
- {
- @Html.AntiForgeryToken()
-
- <div class="form-horizontal">
-
- <hr />
- @Html.ValidationSummary(true, "", new { @class = "text-danger" })
- <div class="form-group">
- @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
- <div class="col-md-10">
- @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Save" class="btn btn-primary" />
- </div>
- </div>
- <hr />
-
-
- </div>
- }
After adding model, view , controller and Repository folder our final solution explorer will be look like as follows,
Now we have done all coding to upload files.
Step 10 : Now run the application.
After running the application initial screen will be look like as follows,
Now click on Add save button without entering the details then the following error message shows which we have defined in model class as,
Now enter the proper details as,
Now click on save button, It will shows the following message after successfully inserting data into database as,
After entering the details click on save button. The details will get added into the database as in the following:
From all the above examples we have learned how to post strongly typed Html.BeginForm view data Into Database using jQuery Ajax In ASP.NET MVC.
Note
- Do a proper validation such as date input values when implementing.
- Download the Zip file of the sample application for a better understanding.
- Make the changes in the web.config file depending on your server details for the connection string.
Summary
I hope this article is useful for all readers, if you have a suggestion then please contact me.
Read more articles on ASP.NET: