Saturday, 16 September 2017
MVC - Json - How to pass Object (class) from View to Controller using Json (JavaScript)
watch this example on YouTube
1. View
<input type="submit" value="Click Me" name="btn" id="btnClick" />
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$("#btnClick").click(function (e) {
var MyUser = {};
MyUser.ID = 123;
MyUser.FName = "FRANK";
MyUser.LName = "ZAPPA";
$.ajax({
url: '@Url.Action("TestFunction", "Home")',
type: "POST",
data: '{usr: ' + JSON.stringify(MyUser) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Success");
},
error: function (xhr, status, error) {
alert("Failed");
}
});
});
});
</script>
}
2. Controller
[HttpPost]
public ActionResult TestFunction(User usr)
{
return Json(new
{
ResultValue = "something here"
});
}
}
public class User
{
public int ID { get; set; }
public string FName { get; set; }
public string LName { get; set; }
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment