0

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.

1
  • Can you post the JSON for data is after you call ko.toJSON? Commented Feb 17, 2013 at 23:59

3 Answers 3

1

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....

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.