How to pass model from view to controller using jQuery

This article will show you how to pass model from view to controller using jQuery. Using the submit button we can do it easily, jQuery use to pass elements as well as we can submit a form using jQuery.

Here is code

Add script “jquery.validate.min.js”

 <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript" > </script>

View page


@model Sample.Models.UserModel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript">
    $(document).ready(function () {
        $('#adduser').click(function (e) {
            e.preventDefault();
            if ($("#addNewUserForm").valid()) { //if you use validation
                $.ajax({
                    url: $("#addNewUserForm").attr('action'),
                    type: $("#addNewUserForm").attr('method'),
                    data: $("#addNewUserForm").serialize(),
                    success: function (data) {
                        alert(data.Status); 
                    }
                });
            }
        });
    });
</script>

@using (Html.BeginForm("AddUSer", "User", FormMethod.Post, new { id = "addNewUserForm" }))
{
    <div>First Name : @Html.TextBoxFor(x => x.FName)</div>
    <div>Last Name : @Html.TextBoxFor(x => x.LName)</div>
    <input id="adduser" type="button" value="Add User" />
}

One more way to do this, data is a serialized to JSON string. Note the name has to match the parameter name in the Model.

    function AddUser() {
        var UserModel =
        {
            "FirstName": "Abc",
            "LastName": "Pqr"
        };
        $.ajax({
            url: '/User/AddUser/',
            data: JSON.stringify(UserModel),
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                // return values 
            }
        });
    }

For the reference code of controller and model

Controller

 public class UserController : Controller
    {
        public ActionResult Index()
        {
            UserModel user = new UserModel();
            return View(user);
        }

        public JsonResult AddUser(UserModel user)
        {
            //  Add user model
            return Json(new { Status = "Success" }, JsonRequestBehavior.AllowGet);
        }
    }

Model

    public class UserModel
    {
        public string FName { get; set; }
        public string LName { get; set; }
    }
Advertisements
This entry was posted in Ajax, jQuery, MVC and tagged , . Bookmark the permalink.

3 Responses to How to pass model from view to controller using jQuery

  1. cezar191 says:

    Excellent thank you

  2. Sagar Moharil says:

    Thanks a lot, it really saved a lot of time. Very much helpful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s