yesman
yesman

Reputation: 7848

Posting to MVC Controller, ViewModel stays null

I have this ASP.NET MVC controller action and viewmodel:

public JsonResult Upload(UploadModel MyModel)
{
    //do stuff with MyModel
}

public class UploadModel
{
    public string Name;
}

And in Angular, a method for submitting a form to this action:

function onSubmit() {
     console.log(vm.model);
     $http.post('/Home/Upload', vm.model).
     then(function (response) 
     { 
         // do stuff with response 
     }); 
};

When I log vm.model, it looks like this:

{ Name : "Some cool name" }

It looks exactly the same in the request payload. But when I post this object to the Upload method, Name appears to be null. However, when I change the Upload method to accept just a string instead of a viewmodel:

public JsonResult Upload(String Name)
{
    //do stuff with Name
}

And post the exact same object to it, it does get recognized.

What is going on? Why isn't MVC recognizing my JS object as a viewmodel?

Upvotes: 2

Views: 149

Answers (2)

REDEVI_
REDEVI_

Reputation: 684

You should serialize your form data and then post

var cpformdata = $("#Myform form").serializeArray();

$.ajax({
            url: url,
            type: 'POST',
            data: cpformdata,
            success: function (data) {
}

Upvotes: 0

user3559349
user3559349

Reputation:

Name is a field, not a property (no getter/setter) so the DefaultModelBinder cannot set the value. Change it to

public class UploadModel
{
    public string Name { get; set; }
}

Upvotes: 4

Related Questions