Thursday, 8 June 2017

Pass (Send) Model object in jQuery $.ajax() POST request to Controller method in ASP.Net MVC

Pass (Send) Model object from View to Controller method in ASP.Net MVC
Description:
In this example we explain that how to pass Model object from View to controller method in Asp.Net MVC. Or how to Send Model Object in jQuery Ajax POST request to controller in MVC.

Here we simply pass the Object of the Model from View to Controller in MVC Razor.so below is the example that demonstrate how to Pass or Send Model Object from View to Controller in MVC using jQuery Ajax Call.
Model:

public class EmployeeModel
{
    ///<summary>
    /// Gets or sets Name.
    ///</summary>
    public string Name { getset; }

    ///<summary>
    /// Gets or sets DateTime.
    ///</summary>
    public string DateTime { getset; }
}

Controller:

public class EmployeeController : Controller
{
    // GET: Home
    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>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</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