通过MVC4中的表单发布JSON数据

时间:2022-12-03 07:40:08

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.

我正在尝试将一个JSON对象(一个JSON-ified淘汰模型,如果有任何相关性)发布到我的MVC控制器,并让控制器返回一个新视图。为此,我将使用表单发送数据。问题是我希望在控制器收到JSON时自动将JSON转换为模型。

If I were to use an AJAX call for this,

如果我为此使用AJAX调用,

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) {
    }
});

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

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

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

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:

如果我想用表单执行此操作,我理解我需要将JSON插入到隐藏的输入字段中,但是在执行此操作时我能够管理的最佳方法是将数据作为序列化字符串接收:

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

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

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?

我之后可以反序列化它,但我真的更喜欢它,如果MVC可以为我转换它,就像使用AJAX调用一样。这可能吗?

Thanks.

谢谢。

2 个解决方案

#1


2  

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.

假设您想使用表单而不是XHR发布编码为json的数据,我认为它不是开箱即用的。

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

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

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.

如果你将json作为字符串发布,它可能可以创建一个模型绑定器,它查找看起来像json的字符串并在那里处理反序列化。不是最漂亮的东西,特别是如果这只是针对一些奇怪的情况。

#2


0  

Instead of the manual deserialization, you can catch the form post event and reconstruct your own post, adding the additional JSON object. Here is an example that uses the serializeObject method from this post):

您可以捕获表单post事件并重新构建自己的帖子,添加额外的JSON对象,而不是手动反序列化。这是一个使用此帖子中的serializeObject方法的示例):

$(document).ready(function () {
    $('form').live('submit', function (e) {
        e.preventDefault();

        var dataToPost = $(this).serializeObject();
        dataToPost.hiddenFieldName = actionModel; //additional object here
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: JSON.stringify(dataToPost),
            contentType: 'application/json; charset=utf-8',
            success: function (res) {
                //do something...
            }
        });
    });
});

#1


2  

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.

假设您想使用表单而不是XHR发布编码为json的数据,我认为它不是开箱即用的。

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

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

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.

如果你将json作为字符串发布,它可能可以创建一个模型绑定器,它查找看起来像json的字符串并在那里处理反序列化。不是最漂亮的东西,特别是如果这只是针对一些奇怪的情况。

#2


0  

Instead of the manual deserialization, you can catch the form post event and reconstruct your own post, adding the additional JSON object. Here is an example that uses the serializeObject method from this post):

您可以捕获表单post事件并重新构建自己的帖子,添加额外的JSON对象,而不是手动反序列化。这是一个使用此帖子中的serializeObject方法的示例):

$(document).ready(function () {
    $('form').live('submit', function (e) {
        e.preventDefault();

        var dataToPost = $(this).serializeObject();
        dataToPost.hiddenFieldName = actionModel; //additional object here
        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: JSON.stringify(dataToPost),
            contentType: 'application/json; charset=utf-8',
            success: function (res) {
                //do something...
            }
        });
    });
});