Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Can JSON object be passed to a controller with parameter with dynamic type parameter?

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

like image 425
mark vanzuela Avatar asked Jul 23 '12 07:07

mark vanzuela


1 Answers

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.

like image 191
nemesv Avatar answered Sep 28 '22 03:09

nemesv