Wednesday, 4 October 2017

How to send a model in jQuery $.ajax() post request to MVC controller method

How to send a model in jQuery $.ajax() post request to MVC controller method
Description:


In this example we explain that how to Pass Model Object in jQuery ajax post request to controller method in Asp.Net MVC.or how to Pass or Send Model Object from Razor View to Controller using jQuery Ajax call in MVC.or how to access Model in Action method of Controller in MVC.or how to call action method of controller using jQuery Ajax call and pass Model Class object to controller method in MVC.
Model:

public class EmployeeModel
    {
     
        public string Name { get; set; }
        public string DateTime { get; set; }
    }

Controller:

public class EmployeeController : Controller
    {

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult AjaxMethod(EmployeeModel employee)
        {
            employee.DateTime = DateTime.Now.ToString();
            return Json(employee);
        }
    }

View: 

@model jQuery_AJAX_Model_MVC.Models.employeeModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Pass (Send) Model object in jQuery $.ajax() POST request to Controller method in ASP.Net MVC</title>
</head>
<body>
    <input type="text" id="txtName"/>
    <input type="button" id="btnGet" value="Get Current Time"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                var employee = {};
                employee.Name = $("#txtName").val();
                $.ajax({
                    type: "POST",
                    url: "/Employee/AjaxMethod",
                    data: '{employee: ' + JSON.stringify(employee) + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Hello: " + response.Name + ".\nCurrent Date and Time: " + response.DateTime);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>


0 comments:

Post a Comment