问题
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:
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....
回答2:
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>
回答3:
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.
来源:https://stackoverflow.com/questions/14927576/controller-action-wont-bind-json-viewmodel