How to pass an ko.observableArray to an MVC controller?
I want to pass an array of strings from my view model (in form of an ko.observableArray
) to the controller in Asp.net MVC.
As the ko.observableArray
is an object rather than array, it cannot simply be passed through the $.ajax
开发者_如何学运维 method and used as array in controller side.
How can I pass the data in ko.observableArray
to controller so that I can use it as array on the controller side?
Knockout has two utility function called ko.toJS
and ko.toJSON
.
var myPlainObject = ko.toJS(root)
will traverse your object and turn any observable into a plain JavaScript property.
var myJSONstring = ko.toJSON(root)
will do the same and then do a JSON.stringify
on the result.
So, you can use those functions on your viewModel to get plain JavaScript objects.
Info from the docs here.
If the items in your observableArray do not contain observables, then you could simply just retrieve the underlying array by doing myObservableArray()
Update: based on comment. This works fine for me:
var viewModel = {
items: ko.observableArray(["one", "two", "three", "four"]),
sendItems: function() {
$.ajax({
type: "POST",
url: "@Url.Action("Test")",
data: ko.toJSON(viewModel.items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data) {
alert(ko.toJSON(data));
}
}
});
}
};
Against an action like:
//just echo back data
public JsonResult Test(List<String> myList)
{
return Json(myList);
}
Does this match what you are trying?
精彩评论