RJP
RJP

Reputation: 4116

Controller Action won't bind JSON ViewModel

Every time I post to my Action, my ViewModel is not null, but all the values inside always are.

Where I have console.log, I can see perfect JSON being output to the console.

Any ideas?

Action:

public ActionResult Add(MyViewModel model)
{
//stuff
}

JS:

<script type="text/javascript">
var model = @Html.Raw(Viewbag.MyJSON);

var viewModelDetails = ko.mapping.fromJS(model);

this.addData = function() {
var data = ko.toJSON(viewModelDetails);
console.log(data);
$.post("/user/add", data, function(result){
//stuff
});
}
</script>

Model

public  MyViewModel()
{
Game Game{get;set;}
}

EDIT:

WOW, I feel dumb, I had private set, so thats what it wasn't getting bound.

Upvotes: 0

Views: 673

Answers (3)

NaveenKumar1410
NaveenKumar1410

Reputation: 1613

I have faced issues like this before.I share you the solution what i made.

Make a change like below

var data = ko.toJS(viewModelDetails);

Note: for this to work on older browsers that have no native JSON serializer (e.g., IE 7 or earlier), you must also reference the json2.js library

I know this will work perfect.If it solves your problem mark it as answer

If it is useful to you then click uplink

Whats the problem in the code:-

var data = ko.toJSON(viewModelDetails);

You need to parse data again as json , then you can use it, else it will get error.

Upvotes: 1

Dave Alperovich
Dave Alperovich

Reputation: 32490

you have to convert your data to json JSON.stringify(result)

<script type="text/javascript">
var model = @Html.Raw(Viewbag.MyJSON);

var viewModelDetails = ko.mapping.fromJS(model);

this.addData = function() {
var data = ko.toJSON(viewModelDetails);
console.log(data);
$.post("/user/add", JSON.stringify(data), function(result){
//stuff
}, 
dataType: json,
traditional: true

);
}
</script>

Upvotes: 1

Mike C.
Mike C.

Reputation: 3114

Give this a try:

$.post("/user/add", data, function(result){
//stuff
}, dataType: json);

What I've had happen in the past, is the default dataType isn't Json, so it doesn't pass it correctly. Might not be what's happening here though....

Upvotes: 1

Related Questions