ASP.NET MVC Can JSON object be passed to a control

2020-04-07 05:56发布

问题:

I have code in my javascript, a ajax to post data:

$.ajax({
                url: '/Configurations/GetSelectedPageTranslation',
                type: 'POST',
                data: { inttype: $("#some").val(), objectType:{prop1: 'adsfa', prop2: 'asdf'}},
                success: function (result) {

                },
                error: function () {
                    alert('error');
                }
            });

In the contoller i have a method with signature:

public JsonResult GetSelectedPageTranslation(int inttype, dynamic objectType)

I can have the inttype correctly. However the objectType will not be null but if i do like objectType.prop1, it will throw error. If i will JSON.stringify the object type in the javascript, the objectType in the controller will have a string value.

Could this be possible to directly access the JSON data in the controller using the dynamic data type like this: objectType.prop1 ?

Thanks

回答1:

There is no out of the box support for dynamic action arguments in MVC3.

However MVC is very extensible so you can add this functionality. What you need to do is to create a custom IModelBinder where you can do the JSON deserialization and build up a dynamic object.

Luckily this article: Making MVC 3 a little more… dynamic is dealing with the exact same problem, so you can find also sample code and additional links there which should help you get started.