Pages

Monday 21 July 2014

Pass Javascript object to MVC controller using Ajax

To pass javascript object follow following steps.

Step 1. Creating Javascript Object:

  var Person = {   
    Id:$("#Id").val(),
    Name:$('#Name').val()
};

Here I created one javascript object named Person with two properties named Id and Name. Here I assigned values from form controls to that properties.

Step 2. Ajax Call to pass data to MVC Controller $.ajax({ url: '@Url.Action("getDetail", "Employee")', data: JSON.stringify({ PersonDetail:Person }), dataType: 'json', type: 'POST', contentType: "application/json", async: true, traditional: true, success: function (result) { alert("result"); } });

In above code I made ajax call to the controller action named getDetail then I passed the javascript obejct to controller via data property of the ajax.

Step 3.Create Model class with all the person properties public class Person { public string Id{ get; set; } public string Name { get; set; } }

In above code I created one Model class with all the Person properties that will get initialised in javascript code.

Step 4. Write controller action which receives the data which sent through ajax. [HttpPost] public JsonResult getDetail(Person PersonDetail) {

Then in controller action the person data is received in person object. Here you will get all the values for the person from PersonDetail object.

No comments:

Post a Comment