Background
In many MVC projects and other applications you might have noticed while inserting data into the database whole post back occurs which consumes the server resources unnecessarily and some time inserts the duplicate records when page is post back again. So to avoid it we will learn how to post the data using jQuery Ajax post method in MVC which will insert the data asynchronously into the database without whole page post back.
You might be interested in one of my ASP.NET article
Inserting Form Data Into DataBase Using Stored Procedure In ASP.NET C# posted in Decemnber 2012 with 149 k+ views and based on the same I decided same functionality article using ASP.NET MVC.
- "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
- "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK.
- Choose MVC empty application option and click on OK
Step 2: Create Model Class.
Right click on Model folder in the created MVC application, give the class name employee or as you wish and click OK.
EmpModel.cs
- public class EmpModel
- {
- public string Name { get; set; }
- public string City { get; set; }
- public string Address { get; set; }
-
- }
Step 3: Create Table and Stored procedures.
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, update, view and delete the details as in the following code snippet:
Step 4: Add controller class.
Right click on
Controller folder in the created MVC application; give the class name. I have given class name Home and clicked OK.
HomeControlle.cs
- public class HomeController : Controller
- {
- private SqlConnection con;
-
-
- public ActionResult AddEmployee()
- {
-
- return View();
- }
-
- [HttpPost]
- public ActionResult AddEmployee(EmpModel obj)
- {
- AddDetails(obj);
-
- return View();
- }
-
-
- private void connection()
- {
- string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
- con = new SqlConnection(constr);
-
- }
-
- private void AddDetails(EmpModel obj)
- {
- connection();
- SqlCommand com = new SqlCommand("AddEmp", con);
- com.CommandType = CommandType.StoredProcedure;
- com.Parameters.AddWithValue("@Name", obj.Name);
- com.Parameters.AddWithValue("@City", obj.City);
- com.Parameters.AddWithValue("@Address", obj.Address);
- con.Open();
- com.ExecuteNonQuery();
- con.Close();
-
- }
- }
Step 5: Add View
Right click on View folder of created MVC application project and add empty view named AddEmployee.cshtml.
Step 6: Create jQuery Post method
Now open the AddEmployee.cshtml view and create the following jQuery Post method to call controller.
- <script>
- $(document).ready(function () {
- //function will be called on button click having id btnsave
- $("#btnSave").click(function () {
- $.ajax(
- {
- type: "POST",
- url: "Home/AddEmployee",
- data: {
- Name: $("#txtName").val(),
- City: $("#txtAddress").val(),
- Address: $("#txtcity").val()
- }
-
- });
-
- });
- });
-
- </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>
Step 7: Add controls on the Razor view.
Now after adding the library and form controls , the AddEmployee.cshtml code will be look like as:
- @{
- ViewBag.Title = "www.compilemode.com";
- }
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- <script>
- $(document).ready(function () {
- $("#btnSave").click(function () {
- $.ajax(
- {
- type: "POST", //HTTP POST Method
- url: "Home/AddEmployee", // Controller/View
- data: { //Passing data
- Name: $("#txtName").val(), //Reading text box values using Jquery
- City: $("#txtAddress").val(),
- Address: $("#txtcity").val()
- }
-
- });
-
- });
- });
-
- </script>
- <br /><br />
- <fieldset>
- <div class="form-horizontal">
- <div class="editor-label">
- Name
- </div>
- <div class="editor-label">
- <input type="text" id="txtName" />
- </div>
-
- <div class="editor-label">
- Address
- </div>
- <div class="editor-label">
- <input type="text" id="txtAddress" />
- </div>
-
- <div class="editor-label">
- City
- </div>
- <div class="editor-label">
- <input type="text" id="txtcity" />
- </div>
- <div class="editor-label">
- <br />
- <input class="btn-default" type="button" id="btnSave" value="Save" />
- </div>
- </div>
- </fieldset>
Now everything is ready, run the application and enter the details into the following form.
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 learned how to insert data using jQuery post method without whole page post back.
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
From all the preceding examples you have learned how to insert data using jQuery post method. I hope this article is useful for all readers, if you have a suggestion then please contact me.