我认为我与knockoutjs绑定。我需要使用ajax post将数据动态添加到viewmodel中的列表。
var data = {
model: ko.toJS(self.Model),
name: name
}
$.ajax({
url: options.url + "AddAdvantage",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
traditional: true,
success: function (data) {
self.UpdateOnChange = false;
ko.mapping.fromJS(data, self.Model);
self.UpdateOnChange = true;
}
});
将data参数传递给控制器操作时:
[HttpPost]
public JsonResult AddAdvantage([ModelBinder(typeof(AdvantageModelBinder))] AdvantageViewModel model, string name) {
}
传递名称值,但模型始终为空
我试过这个:
var data = {
model: ko.toJSON(self.Model),
name: name
}
也尝试过:
var data = JSON.stringify({
model: ko.toJSON(self.Model),
name: name
});
同样的结果。
这很好用:
$.ajax({
url: options.url + "AddAdvantage",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: ko.toJSON(self.Model),
traditional: true,
success: function (data) {
self.UpdateOnChange = false;
ko.mapping.fromJS(data, self.Model);
self.UpdateOnChange = true;
}
});
我的ModelBinder
public class AdvantageModelBinder: DefaultModelBinder
{
public AdvantageModelBinder()
{
}
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
ValueProviderResult value = bindingContext.ValueProvider.GetValue("WizardType");
Type typeByTypeName = AdvantageModelBinder.GetTypeByTypeName((string)value.ConvertTo(typeof(string)));
object obj = Activator.CreateInstance(typeByTypeName);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => obj, typeByTypeName);
return obj;
}
public static Type GetTypeByTypeName(string typeName)
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int i = 0; i < (int)assemblies.Length; i++)
{
Type type = assemblies[i].GetType(typeName, false, true);
if (type != null)
{
return type;
}
}
throw new ArgumentException("Can't find the specified type in the loaded assemblies.", typeName);
}
}
有人能说出如何解决这个问题吗?
答案 0 :(得分:1)
似乎您没有在有效负载中传递完全相同的对象。
让我们说你的模型对象是这样的:
{
foo: 1,
bar: 2
}
在前两个样本上,您正在创建此对象:
{
model: {
foo: 1,
bar: 2
},
name: "whatever"
}
因此,当您将其作为参数传递给ajax调用时,您将传递一个在MVC端不期望的对象。
如果要将其存储在变量中,则需要执行以下操作:
var data = ko.toJSON(self.model)
让ajax调用这样做:
$.ajax({
url: options.url + "AddAdvantage",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: data,
traditional: true,
success: function (data) {
self.UpdateOnChange = false;
ko.mapping.fromJS(data, self.Model);
self.UpdateOnChange = true;
}
});
答案 1 :(得分:0)
试试这个:
var data = {
model: self.Model,
name: name
}
$.ajax({
url: options.url + "AddAdvantage",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: ko.toJSON(data),
traditional: true,
success: function (data) { ... }
});