Wednesday, 13 April 2016

How to pass View values to Controller using Jquery

Leave a Comment
We know how to pass data to the controller using Model binding.In this article i am going to explain how to pass the form data from View page to Controller and store the data in Sql server table.
I will explin this in step by step manner.
If you are new to ASP.NET MVC please refer previous tutorials for basics of MVC.

Step 1: Create a MVC web application
1.open visual studio and create a ASP.NET MVC web application and name it Jquery.
Step 2: Create Model class
1.right click Models folder -->Add-->Class-->name it User.cs
2. Create following properties in User.cs Model class.

 public class User
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
    }

Step 3: Add Controller
1.Right click controller folder
2.Add-->New-->Controller-->Name it HomeController.cs
HomeController.cs

using System.Data;
using System.Data.SqlClient;
using Jquery.Models;
using System.Configuration;
namespace Jquery.Controllers
{
    public class HomeController : Controller
    {
        private SqlConnection con;

        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult AddUser(User 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(User obj)
        {
            connection();
            string query = "insert into UserData values(@Name,@City,@Address)";
            SqlCommand com = new SqlCommand(query, con);
            com.CommandType = CommandType.Text;
            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 4: Add View page
1.right click on Index action method and add View
2.name it Index.cshtml.
3.In index view add following jquery code

@*Add jquery CDN to the View page*@
    $(document).ready(function () {
        $("#btnSave").click(function () {
            $.ajax(
            {
                type: "POST", //HTTP POST Method
                url: "Home/AddUser", //data sent to the AddUser action method
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }
            });
        });
    });
Note: Add jquery CDN to View
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Now add Form to enter values.
@{
    ViewBag.Title = "Add User";
}
@*Add jquery CDN to the View page*@
<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/AddUser", //data sent to the AddUser action method
                data: { //Passing data
                    Name: $("#txtName").val(), //Reading text box values using Jquery
                    City: $("#txtAddress").val(),
                    Address: $("#txtcity").val()
                }
            });
        });
    });
</script>
<h2>www.Mitechdev.com user data</h2>
<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>
Step 5: Create a table

Now run the application and see in browser..

Enter some data into Fields and click submit and check the data was inserted into the Database or not.
Check below image data you entered in the fields successfuly inserted into Table.

Download the sample code for this application here Download.

Conclusion:
I hope this article is understanble for any people and you learn from this article.


0 comments:

Post a Comment