Description:
Model:
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.
public class EmployeeModel
{
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
///<summary>
/// Gets or sets DateTime.
///</summary>
public string DateTime { get; set; }
}
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