Post MVC Model Using JQuery

Post MVC Model Using JQuery

Added by Nasir Mahmood updated on Friday, November 17, 2017

Problem:

This tutorial is a comprehensive introduction to the problem How to Post MVC Model Using JQuery.

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.

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected