通过MVC4表单POST JSON数据 [英] Post JSON data through a form in MVC4

查看:524
本文介绍了通过MVC4表单POST JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想发布一个JSON对象(JSON-指明分数淘汰赛模式,如果这是任何相关性),以我的MVC控制器,并有控制器返回一个新的观点。要做到这一点,我有一个表单发送数据。问题是,我想有当控制器接收到它的JSON自动转换为模型。

I'm trying to POST a JSON object (a JSON-ified knockout model, if that's of any relevance) to my MVC controller, and have the controller return a new view. To do this, I'm sending the data with a form. The problem is that I would like to have the JSON automatically converted to a model when the controller receives it.

如果我是用AJAX调用此,

If I were to use an AJAX call for this,

var actionModel = new Object();
actionModel.Controls = ko.toJS(self.controls());
var json = JSON.stringify(actionModel);
$.ajax({
    url: "MyController/Preview",
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    cache: false,
    data: json,
    success: function (data) {
    }
});

... JSON对象成功反序列化,并转换成我的模型类的一个实例。

...the JSON object is successfully deserialized and converted into an instance of my model class.

public ActionResult Preview(ActionModel actionModel) { ... }
public class ActionModel
{
    public List<ControlModel> Controls { get; set; }
}

如果我想用形式要做到这一点,我知道我需要的JSON插入一个隐藏的输入字段,但最好这样做是接收数据作为序列化的字符串时,我可以管理:

If I want to do this with a form, I understand that I need to insert the JSON into a hidden input field, but the best I can manage when doing this is to receive the data as a serialized string:

@using (Html.BeginForm("Preview", "MyController", FormMethod.Post, new { id = "previewForm" }))
{
    <input type="hidden" id="hiddenFieldName" />
}

public ActionResult Preview(string hiddenFieldName) { ... }

我可以反序列化之后,但我真的想preFER,如果MVC可以转换对我来说,因为它会与一个AJAX调用。这可能吗?

I could just deserialize it afterwards, but I really would prefer it if MVC could convert it for me, as it would with an AJAX call. Is this possible?

感谢。

推荐答案

假设你想用一种形式,没有XHR张贴EN $ C $光盘作为JSON数据,我不认为这是开箱即用的可能。

Assuming you want to post data encoded as json using a form and no XHR, I don't think it's out of the box possible.

表格不允许许多内容类型。 http://www.w3.org/TR/html401 /interact/forms.html#form-content-type

Forms don't allow many content types. http://www.w3.org/TR/html401/interact/forms.html#form-content-type

如果您发布JSON作为一个字符串,它可能可以创建查找这似乎是JSON和反序列化与处理字符串有一个模型粘合剂。不是prettiest的事情,尤其是如果这只是一些一次性奇怪的情况。

If you post json as a string, its probably possible to create a model binder that looks for strings which appear to be json and deal with deserialization there. Not the prettiest thing, especially if this is just for some one off odd situation.

这篇关于通过MVC4表单POST JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆