使用jQuery.post将多个参数发布到MVC Controller

时间:2022-12-05 17:02:25

I have a controller defined as:

我有一个控制器定义为:

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult PostMoreData(DataContracts.Address address, DataContracts.GeoLocation geoLocation)
        {
            return Json("test");
        }

where DataContracts.Address and DataContracts.GeoLocation are complex types.

From my View i'm trying to post using jQuery as such:

从我的视图我试图使用jQuery发布如下:

        function PostMoreData() {

            var JsonAddress = {

                "Building": $('Building').val(),
                "UnitNumber": $('UnitNumber').val(),
                "StreetNumber": $('StreetNumber').val(),
                "StreetName": $('StreetName').val(),
                "StreetType": $('StreetType').val(),
                "Suburb": $('Suburb').val(),
                "State": $('State').val(),
                "Postcode": $('Postcode').val(),
                "MonthsAtAddress": $('MonthsAtAddress').val()

            };

            var JsonGeoLocation = {
                "Latitude": $('Latitude').val(),
                "Longitude": $('Longitude').val()
            };


            jQuery.post("/AddressValidation/PostMoreData", {address: JsonAddress, geoLocation: JsonGeoLocation}, function(data, textStatus) {
                if (textStatus == "success") {
                    var result = eval(data);
                    if (result.length > 0) {
                        alert(result);
                    }
                }
            }, "json");
        } 

However, on the controller, I get nulls.

但是,在控制器上,我得到空值。


It works if my Controller takes just 1 argument and I post just one object.

它可以工作,如果我的控制器只需要一个参数,我只发布一个对象。

        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult PostMoreData(DataContracts.Address address)
        {
            return Json("test");
        }
        function PostMoreData() {

            var JsonAddress = {

                "Building": $('Building').val(),
                "UnitNumber": $('UnitNumber').val(),
                "StreetNumber": $('StreetNumber').val(),
                "StreetName": $('StreetName').val(),
                "StreetType": $('StreetType').val(),
                "Suburb": $('Suburb').val(),
                "State": $('State').val(),
                "Postcode": $('Postcode').val(),
                "MonthsAtAddress": $('MonthsAtAddress').val()

            };


            jQuery.post("/AddressValidation/PostMoreData", JsonAddress, function(data, textStatus) {
                if (textStatus == "success") {
                    var result = eval(data);
                    if (result.length > 0) {
                        alert(result);
                    }
                }
            }, "json");
        } 

Any ideas how i can post more than one object?

我可以发布多个对象的任何想法?

4 个解决方案

#1


3  

Note that the "default serialization" that jQuery is doing here isn't going to work no matter what your controller does. jQuery doesn't "traverse" the parameter map below the first level, so the example in the question is likely generating this post data:

请注意,无论您的控制器做什么,jQuery在这里执行的“默认序列化”都不会起作用。 jQuery不会“遍历”第一级下面的参数映射,因此问题中的示例可能会生成此发布数据:

address=[object]&geoLocation=[object]

The other, working example does not contain any sub-objects, so it is being translated directly, like this:

另一个工作示例不包含任何子对象,因此它是直接翻译的,如下所示:

Building=value&UnitNumber=value&...&MonthsAtAddress=value

The easiest fix is making the parameter map flat, each key prefixed with either 'Address.' or 'GeoLocation.', depending.

最简单的解决方法是使参数映射平坦,每个键都以“地址”为前缀。或'GeoLocation。',取决于。

#2


3  

Thank you everyone for your input on this issue.

感谢大家对此问题的意见。

At this stage, we have departed from using jquery to post complex types to controllers. Instead we use the ms ajax framework to do that. ms ajax post nicely binds the complex types automatically out of the box.

在这个阶段,我们已经不再使用jquery将复杂类型发布到控制器。相反,我们使用ms ajax框架来做到这一点。 ms ajax post很好地自动绑定复杂类型开箱即用。

So our solution now uses a mix of jquery and ms ajax framework.

所以我们的解决方案现在使用jquery和ms ajax框架的混合。

Ash

#3


2  

Your code requires that the way jquery serializes an object is compatible with the MVC default model binder, which I think is unlikely.

您的代码要求jquery序列化对象的方式与MVC默认模型绑定器兼容,我认为这不太可能。

If you can build your javascript object so that it serializes as a flat object with dot notation (JsonAddress.Building) that would work, or you can let jquery do the default serialization and then create a custom model binder to deserialize to the action parameter types.

如果您可以构建您的javascript对象,以便将其序列化为带有点符号(JsonAddress.Building)的平面对象,或者您可以让jquery执行默认序列化,然后创建自定义模型绑定器以反序列化为action参数类型。

#4


0  

I had the same problem and couldn't get anything to work. Also someone raised it as a bug with jquery and they closed it as not a bug.

我有同样的问题,无法得到任何工作。还有人提出它作为jquery的bug,他们关闭它不是一个bug。

I have found a few solutions which answer part of the whole question. And the answer includes the following.

我找到了一些解决整个问题部分问题的解决方案。答案包括以下内容。

1) Client side: we would need to stringyfy all the objects you need to send. This could be a normal object or an array. It works on both.

1)客户端:我们需要将您需要发送的所有对象变为stringyfy。这可以是普通对象或数组。它适用于两者。

2) Client side: You send the data as you have in the first post. As you would object by object.

2)客户端:您在第一篇文章中发送数据。正如你所反对的那样。

Tip: When you send parameterised objects, jquery encodes the data sent to the server.

提示:发送参数化对象时,jquery会对发送到服务器的数据进行编码。

Following all are server side implementations 1) Deserializer class: which will take the input string and put it back in to object/list<>/IList<> what ever you have defined as datatype of the parameter of the controller function. You would need to implement ActionFilterAttribute for the above.

接下来是服务器端实现1)反序列化器类:它将获取输入字符串并将其放回到对象/列表<> / IList <>,您已将其定义为控制器函数的参数的数据类型。您需要为上面的内容实现ActionFilterAttribute。

2) Finally add an attribute to controller function, so that it uses the deserialiser class to get the parameters.

2)最后向控制器函数添加一个属性,以便它使用deserialiser类来获取参数。

As this is quite a lot of code let me know if you need details or have you solved the problem.

由于这是很多代码,如果您需要详细信息或者您已解决问题,请告诉我。

Deepak Chawla

#1


3  

Note that the "default serialization" that jQuery is doing here isn't going to work no matter what your controller does. jQuery doesn't "traverse" the parameter map below the first level, so the example in the question is likely generating this post data:

请注意,无论您的控制器做什么,jQuery在这里执行的“默认序列化”都不会起作用。 jQuery不会“遍历”第一级下面的参数映射,因此问题中的示例可能会生成此发布数据:

address=[object]&geoLocation=[object]

The other, working example does not contain any sub-objects, so it is being translated directly, like this:

另一个工作示例不包含任何子对象,因此它是直接翻译的,如下所示:

Building=value&UnitNumber=value&...&MonthsAtAddress=value

The easiest fix is making the parameter map flat, each key prefixed with either 'Address.' or 'GeoLocation.', depending.

最简单的解决方法是使参数映射平坦,每个键都以“地址”为前缀。或'GeoLocation。',取决于。

#2


3  

Thank you everyone for your input on this issue.

感谢大家对此问题的意见。

At this stage, we have departed from using jquery to post complex types to controllers. Instead we use the ms ajax framework to do that. ms ajax post nicely binds the complex types automatically out of the box.

在这个阶段,我们已经不再使用jquery将复杂类型发布到控制器。相反,我们使用ms ajax框架来做到这一点。 ms ajax post很好地自动绑定复杂类型开箱即用。

So our solution now uses a mix of jquery and ms ajax framework.

所以我们的解决方案现在使用jquery和ms ajax框架的混合。

Ash

#3


2  

Your code requires that the way jquery serializes an object is compatible with the MVC default model binder, which I think is unlikely.

您的代码要求jquery序列化对象的方式与MVC默认模型绑定器兼容,我认为这不太可能。

If you can build your javascript object so that it serializes as a flat object with dot notation (JsonAddress.Building) that would work, or you can let jquery do the default serialization and then create a custom model binder to deserialize to the action parameter types.

如果您可以构建您的javascript对象,以便将其序列化为带有点符号(JsonAddress.Building)的平面对象,或者您可以让jquery执行默认序列化,然后创建自定义模型绑定器以反序列化为action参数类型。

#4


0  

I had the same problem and couldn't get anything to work. Also someone raised it as a bug with jquery and they closed it as not a bug.

我有同样的问题,无法得到任何工作。还有人提出它作为jquery的bug,他们关闭它不是一个bug。

I have found a few solutions which answer part of the whole question. And the answer includes the following.

我找到了一些解决整个问题部分问题的解决方案。答案包括以下内容。

1) Client side: we would need to stringyfy all the objects you need to send. This could be a normal object or an array. It works on both.

1)客户端:我们需要将您需要发送的所有对象变为stringyfy。这可以是普通对象或数组。它适用于两者。

2) Client side: You send the data as you have in the first post. As you would object by object.

2)客户端:您在第一篇文章中发送数据。正如你所反对的那样。

Tip: When you send parameterised objects, jquery encodes the data sent to the server.

提示:发送参数化对象时,jquery会对发送到服务器的数据进行编码。

Following all are server side implementations 1) Deserializer class: which will take the input string and put it back in to object/list<>/IList<> what ever you have defined as datatype of the parameter of the controller function. You would need to implement ActionFilterAttribute for the above.

接下来是服务器端实现1)反序列化器类:它将获取输入字符串并将其放回到对象/列表<> / IList <>,您已将其定义为控制器函数的参数的数据类型。您需要为上面的内容实现ActionFilterAttribute。

2) Finally add an attribute to controller function, so that it uses the deserialiser class to get the parameters.

2)最后向控制器函数添加一个属性,以便它使用deserialiser类来获取参数。

As this is quite a lot of code let me know if you need details or have you solved the problem.

由于这是很多代码,如果您需要详细信息或者您已解决问题,请告诉我。

Deepak Chawla