Passing View Values To Controller Using jQuery Ajax In ASP.NET MVC

In this article we will learn how to pass values to model class using Jquery in ASP.Net MVC.
So let's demonstrate it by creating simple MVC application.
Step 1 : Create an MVC Application.
Now let us start with a step by step approach from the creation of simple MVC application as in the following:
  1. "Start", then "All Programs" and select "Microsoft Visual Studio 2015".
  2. "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 . 
 Step 2 : Add Model class
Right click on model folder of created MVC application project and add class named Empmodel.cs
Empmodel.cs
public class EmpModel
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Address { get; set; }
        
    }
 Step 2 : Add Controller
 HomeController.cs
public class HomeController : Controller
    {
        private SqlConnection con;
       
        // GET: Home
        public ActionResult AddEmployee()
        {
           
            return View();
        }
        //Post method to add details
        [HttpPost]
        public ActionResult AddEmployee(EmpModel obj)
        {
            AddDetails(obj);

            return View();
        }

        //To Handle connection related activities
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["SqlConn"].ToString();
            con = new SqlConnection(constr);

        }
        //To add Records into database 
        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 3: Add View
Right click on View folder of created MVC application project and add empty view named AddEmployee.cshtml
 Step 4: Create Jquery Post method
Now open the AddEmployee.cshtml view and create the following JQuery Post method to call controller .
<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>
Note
  • To work with jQuery we need to reference of jQuery library  .You can use following CDN jQuery library 
or you can use same file by downloading it as offline jQuery file.
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 then the details will be get added into the database as





From all above example we have learned passing values to model Class using jQuery In ASP.NET MVC
Note
  • Do a proper validation such as date input values when implementing.
  • 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.

Post a Comment

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode