2

I have 3 classes with below definition

  public class UserRole
    {
        public User User { get; set; }
        public IEnumerable<Role> Role { get; set; }
    }
public class Role
{
   public int Id{ get; set; }
   public string RoleName{ get; set; }
}
public class User
{
   public int Id{ get; set; }
   public string UserName{ get; set; }
}

This is the action method:

  // GET: /Admin/UserManagement/Create
        [HttpPost]
        [Transaction]
        public ActionResult Save(UserRole userrole)
        {
        }

Is there a way in Jquery to serialize some JavaScript vars into a class Obj and then send it to an MVC controller action via an AJAX post?

Shahin
  • 12,543
  • 39
  • 127
  • 205
  • When you create a question, it usually shows related questions based on what you're typing. Did you look at them? The following link seems *very* similar to yours: http://stackoverflow.com/questions/6031206/posting-array-of-json-objects-to-mvc3-action-method-via-jquery-ajax – MilkyWayJoe Apr 24 '12 at 01:54

2 Answers2

17

You could send a JSON request:

var data = {
    user: {
        id: 5,
        userName: 'john'
    },
    role : [
        { id: 1, roleName: 'role 1' },
        { id: 2, roleName: 'role 2' },
        { id: 3, roleName: 'role 3' }
    ]
};

$.ajax({
    url: '@Url.Action("Save")',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(data),
    success: function(result) {
        alert('success');
    }
});

The JSON.stringify method is natively built into modern browsers but if you need to support legacy browsers you could include the json2.js script.

Shahin
  • 12,543
  • 39
  • 127
  • 205
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

The easiest way to do it out-of-the box with all the parts happy (jQuery, MVC Framework) is to serialize the object graph as JSON data on the client and pass that into the POST. The MVC Framework is actually quite good at sorting the model binding out for you.

There is a downloadable sample with a similar complex object here: http://theycallmemrjames.blogspot.ca/2010/05/aspnet-mvc-and-jquery-part-4-advanced.html

It deals with model binding in a number of different scenarios. Check out the suitcase example for your needs. Disclaimer: It's my blog, hope that doesn't offend.

Cheers.

MisterJames
  • 3,306
  • 1
  • 30
  • 48