gdubs gdubs - 2 months ago 11
AngularJS Question

$http post from angularjs to C# MVC view model, have correct List count but the values are null

I have the following post request using $http

var registration = {
userId: 23,
groupings: [
{ Id: 1, Name: 'Test Group 1', Description: 'Yo' },
{ Id: 4, Name: 'Test Group 4', Description: 'Er' }
]
}
$http({
method: 'POST',
url: url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: $.param({
code: eventCode,
UserId: registration.userId
Groupings: registration.groupings
})
})


And then on my action

[HttpPost]
public ActionResult New(string code, RegistrationVM model)
{
:
:
:
}


public class RegistrationVM
{
public int UserId {get;set;}
public IEnumerable<GroupingVM> Groupings { get; set; }
}

public class GroupingVM{
public int Id {get;set;}
public string Name {get;set;}
public string Description {get;set;}

public int AnotherPropertyId {get;set;}
public ANewClass ANewClass {get;set;}
}


Whenever the post happens, I would have the model properties reflect what I posted except the IEnumerable (Groupings) property. Let's say I post with 2 objects on the Groupings property, when I go to the Action, the Groupings property will have a count of 2 but every instance would have either NULL or 0 values on each object. I'm trying to figure out how I'm messing the post.

Answer

First, make the controller take one object as a parameter. Add the "string code" to the RegistrationVM and remove the string code as a parameter.

Then do the same when you create the client object.

Secondly, instead of using the content type "x-www-form-urlencoded" use the "application/json" which is better suited to pass objects.

Before posting the data you need to stringify the obj with data: JSON.stringify(registration)

For more details, read the comments on the question.

Comments