提交JSON来MVC3行动 [英] Submit json to MVC3 action
问题描述
我有Knockout.js创建的窗体。当用户presses提交按钮,我转换视图模型回模型,我试图提交到服务器。我想:
I have a form created with Knockout.js. When the user presses the submit button, I convert the viewmodel back in a model and am trying to submit to the server. I tried:
ko.utils.postJson(location.href, ko.toJSON(viewModel));
但对象是空白的,当它击中了服务器。我切换到这个code:
But the object was blank when it hit the server. I switched to this code:
$.ajax({
url: location.href,
type: "POST",
data: ko.toJSON(viewModel),
datatype: "json",
contentType: "application/json charset=utf-8",
success: function (data) { alert("success"); },
error: function (data) { alert("error"); }
});
这是获取数据使用正确的数据的服务器在里面。
That gets the data to the server with the correct data in it.
但是我想是已提交的数据,所以我的控制器可重定向到正确的观点。有什么建议?
推荐答案
史蒂夫·桑德森有演示得到提交JSON数据将在这里你的控制器动作正确绑定一个较旧的示例:<一href=\"http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/\">http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
Steve Sanderson has an older sample that demonstrates getting submitted JSON data to be bound properly in your controller action here: http://blog.stevensanderson.com/2010/07/12/editing-a-variable-length-list-knockout-style/
它的要点是,他创建了一个名为FromJson的属性,看起来像:
The gist of it is that he creates an attribute called "FromJson" that looks like:
public class FromJsonAttribute : CustomModelBinderAttribute
{
private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
}
然后,操作如下:
Then, the action looks like:
[HttpPost]
public ActionResult Index([FromJson] IEnumerable<GiftModel> gifts)
现在,你可以使用ko.utils.postJson来提交您的数据和应对具有相应的视图。
Now, you could use ko.utils.postJson to submit your data and respond with an appropriate view.
这篇关于提交JSON来MVC3行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!