发布序列化的形式数据和其他数据来MVC控制器? [英] Posting serialized form data AND additional data to MVC controller?

查看:115
本文介绍了发布序列化的形式数据和其他数据来MVC控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上一些额外的数据发送钉到我的服务器POST请求。最初,我只是发送几种形式的信息价值:

I'm trying to tack on some additional data a POST request sent to my server. Originally, I was sending just several forms worth of information:

$.ajax({
    url: 'SaveAllDetails',
    type: 'POST',
    data: $('form').serialize(),
    dataType: 'json'
});

和MVC控制器方法:

and the MVC Controller method:

[HttpPost]
public ActionResult SaveAllDetails([Bind(Prefix = "order")]ExistingOrderDetailsModel existingOrderDetailsModel, 
    [Bind(Prefix = "task")]ExistingTaskDetailsModel existingTaskDetailsModel, [Bind(Prefix = "device")]DeviceDetailsModel deviceDetailsModel)
{
    ....
}

这个伟大的工程。 MVC的模型绑定能够正确地反序列化URL恩codeD字符串。

This works great. MVC's model binder is able to correctly de-serialize the URL-encoded string.

现在,需求发生了变化。我需要用我的三种形式一起发送额外的数据阵列。数据的这个阵列是不是一个形式中保持和不具有结合preFIX。我需要做的这一切都在同一个控制器的方法,因为所有验证需要在单个事务内执行。

Now, requirements have changed. I need to send an additional array of data along with my three forms. This array of data is not held within a form and does not have a binding prefix. I need to do this all in the same Controller method because all validation needs to be performed inside of a single transaction.

所以,现在我已经得到了:

So, I've now got:

var subcomponentsGridRows = JSON.stringify(subcomponentsDetailsView.getAllGridData());
var existingOrderDetailsFormData = $('form#existingOrderDetailsForm').serialize();
var existingTaskDetailsFormData = $('form#existingTaskDetailsForm').serialize();
var deviceDetailsFormData = $('form#existingDeviceDetailsForm').serialize()

$.ajax({
    url: 'SaveAllDetails',
    type: 'POST',
    data: {
        existingOrderDetailsModel: existingOrderDetailsFormData,
        existingTaskDetailsModel: existingTaskDetailsFormData,
        deviceDetailsModel: deviceDetailsFormData,
        subcomponentsGridRows: subcomponentsGridRows
    },
    dataType: 'json'
});

这不为至少一个工作的原因。每个表单重新psented作为一个URL连接codeD字符串$ P $。 subcomponentsGridRows是一个JSON结构。 MVC模型粘合剂是不能够在一个走得太远,因为我可以告诉破译这两种类型的信息。

This doesn't work for at least one reason. Each form is represented as a URL-encoded string. subcomponentsGridRows is a JSON structure. The MVC model binder isn't capable of deciphering both types of information in one go as far as I can tell.

什么是去解决这个问题的好办法吗?

What's a good way to go about tackling this problem?

推荐答案

您可能会发现 以下插件 有用的。

You might find the following plugin useful.

下面是如何它可能对你有用。让我们先通过清洗你的控制器动作定义视图模型:

Here's how it might be useful to you. Let's start by cleaning your controller action by defining a view model:

public class MyViewModel
{
    public ExistingOrderDetailsModel Order { get; set; }
    public ExistingTaskDetailsModel Task  { get; set; }
    public DeviceDetailsModel Device  { get; set; }

    public AdditionalRowsViewModel[] AdditionalRows { get; set; }
}

在这个例子中, AdditionalRowsViewModel 显然会抱着你试图传递给控制器​​动作的附加信息。

In this example the AdditionalRowsViewModel will obviously hold the additional information you are trying to pass to the controller action.

和那么你的控制器动作将变为:

And then your controller action will become:

[HttpPost]
public ActionResult SaveAllDetails(MyViewModel model)
{
    ....
}

OK,这一步是绝对必要的,它只是当我看到一个控制器动作时间超过1的参数我简单地定义一个视图模型。

OK, this step was absolutely necessary, it's just that when I see a controller action taking more than 1 parameter I simply define a view model.

最后,让我们调整我们的AJAX调用:

And finally let's adapt our AJAX call:

$.ajax({
    url: 'SaveAllDetails',
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        order: $('form#existingOrderDetailsForm').serializeObject(),
        task: $('form#existingTaskDetailsForm').serializeObject(),
        device: $('form#existingDeviceDetailsForm').serializeObject(),
        additionalRows: subcomponentsDetailsView.getAllGridData()
    }),
    success: function(result) {
        // do something with the result of the AJAX call here
    }
});

事情需要注意:


    在AJAX请求'JSON'参数:
  1. 摆脱这种数据类型。您正在使用ASP.NET MVC和希望您从控制器动作是在内容类型响应头成功地设置为返回Jsonresult正确的值。 jQuery是足够的智能使用此响应头和pre-过程中的结果变量将被传递到成功您的AJAX请求的回调。因此,在这种情况下,你会得到已经JavaScript对象

  2. 因为你在你的AJAX请求发送JSON的服务器,您需要正确指定的contentType:应用程序/ JSON 参数。否则,你怎么能指望的ASP.NET MVC会知道客户端发送JSON和应用正确的模型绑定?顺便说一下默认的Content-Type请求头的jQuery将发送是应用程序/ x-WWW的形式urlen codeD ,因此,如果您要发送JSON有效载荷您的POST请求,这将是该协议的冲突和侵犯。

  1. Get rid of this dataType: 'json' parameter in your AJAX request. You are using ASP.NET MVC and hopefully you are returning a Jsonresult from your controller action which is successfully setting the Content-Type response header to the correct value. jQuery is intelligent enough to use the value of this response header and pre-process the result variable that will be passed to the success callback of your AJAX request. So in this case you will already get a javascript object
  2. Since you are sending JSON to the server in your AJAX request you need to properly specify the contentType: application/json parameter. Otherwise how do you expect that ASP.NET MVC will know that the client is sending JSON and apply the correct model binder? By the way the default Content-Type request header that jQuery will send is application/x-www-form-urlencoded, so if you are sending JSON payload in your POST request that would be a conflict and violation of the protocol.

这篇关于发布序列化的形式数据和其他数据来MVC控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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