Wednesday, February 12, 2014

Ajax posting object to MVC action

This is the object to be passed:

public class Customer
{
public int Id{get;set;}
public string Name {get;set;}
}
 
Ajax posting with:
- JSON.stringify is used to render the value to the object Customer
- data type is 'json'

  function SubmitButtonOnclick() {        
               $.ajax({
                    type: "POST",
                    url: '@Url.Action("AddUser", "User")',               
                    data: JSON.stringify({
                            Id: $("#Id").val(),
                           Name: $("#Name").val()   }),
                    dataType: 'json',                    
                    contentType: "application/json; charset=utf-8",

                    success: function (response) {

                         alert('response '+ response);
                    },
                    error: function (error) {
                         alert('error ' + error);
                    }
                 });
            }


In the "User" controller file:
[HttpPost]
public ActionResult AddUser(Customer customer)
{
 // perform your code
}

No comments:

Post a Comment