通过MVC4中的表单发布JSON数据 [英] Post JSON data through a form in MVC4

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

问题描述

我正在尝试向我的 MVC 控制器发布一个 JSON 对象(一个 JSON 化的淘汰模型,如果这有任何相关性),并让控制器返回一个新视图.为此,我使用表单发送数据.问题是我希望在控制器接收到 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) { ... }

之后我可以反序列化它,但如果 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 发布编码为 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 的字符串并在那里处理反序列化.不是最漂亮的事情,尤其是如果这只是为了一些奇怪的情况.

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中的表单发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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