【发布时间】:2013-03-19 19:05:31
【问题描述】:
我想将 FeatureList (observableArray) 中的数据传递给 TreeController 中的 SaveMappings 函数。我已将一个按钮绑定到 sendItems 函数。我在 var data=p2fData 行放了一个断点,看看我收到了什么。 p2fData 为空。
我将控制器更改为公共 JsonResult SaveMappings(List p2fData)。在这种情况下,p2f 数据显示有 1 个元素,但它也为空。
var Feature = function (featId) {
var self = this;
self.featId = featId;
self.parameters = ko.observableArray();
}
var ParameterToFeatureListViewModel = function () {
var self = this;
var newFeature = new Feature("Feature XYZ");
newFeature.parameters.push("1");
newFeature.parameters.push("2");
self.FeatureList = ko.observableArray([newFeature]);
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Tree/SaveMappings',
data: ko.toJSON(self.FeatureList),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ParameterToFeatureListViewModel()
ko.applyBindings(vm);
public class TreeController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public JsonResult SaveMappings(string p2fData)
{
var data = p2fData;
return Json(data);
}
}
【问题讨论】:
-
你没有在 SaveMappings 中有一些真正的 C# 类型作为参数吗?为什么要将所有数据作为 JSON 格式存储在字符串中?但是,如果您想使用 JSON,请尝试使用
data: JSON.stringify({ p2fData: ko.toJSON(self.FeatureList)}), -
在我执行 JSON.stringify 之后,我确实从 FeaturedList 中获取了数据。我以为 ko.toJSON 做了同样的事情。