通过MVC4表单POST JSON数据

编程入门 行业动态 更新时间:2024-10-28 10:31:16
本文介绍了通过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.

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

Forms don't allow many content types. www.w3/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数据

本文发布于:2023-10-12 00:59:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   数据   JSON   POST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!