Saturday, July 11, 2015
Vikas Sharma
Normally we can post MVC Model by from submission using normal
posting or by JQuery quite easily. But how to post MVC Model without
using form will address in this tutorial.
MVC Model:
A model represents the state of a particular aspect of the application. For this example we use following Model class.
- public class TestModel
- {
- public string Email { get; set; }
- public string Name { get; set; }
- public string Address { get; set; }
- }
-
MVC Controller:
A controller handles interactions and updates the model to reflect
a change in state of the application, and then passes information to
the view.
For this example we use following Controller class.
- [HttpPost]
- public JsonResult TestResult(TestModel model)
- {
- return Json(new { Result = model });
- }
-
Posting Model to Controller:
The magic is using JSON.stringify() function this will
convert our data to json object which must be similar as our Model. Next
contentType must be application/json otherwise server cannot understand
how to map this json object back to Model.
- var postdata = JSON.stringify({
- 'Email': 'myemail@site.com',
- 'Name' : 'Nasir Mahmood',
- 'Address' : 'My Address'
- });
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "/TestResult",
- data: postdata,
- dataType: "json",
- success: function (result) {
-
- }
- });
-
Now if every thing is ok our result contains data which we sent from client side.
0 comments:
Post a Comment