Search code examples
jqueryajaxasp.net-mvcjson.netasp.net-apicontroller

Passing Json data to MVC controller - Action Method's JObject Parameter


Sorry for the wrong formatting or spelling. As i am writting this post in hurry. :)

I am passing json data to action method of simple controller (MVC controller). Here is the below sample code for reference.

JS CODE:

var json = {IsInit :true, SearchParam:{ Type:"xx",Name:"xx",sort: ""} };

    Nx$(document).ready(function () {

        Nx$.ajax({
            async: true,
            contentType: "application/json; charset=utf-8",
            type: "POST",
            url: "Home/Data",
            dataType: "json",
            data: JSON.stringify(json),
            success: function (msg) {
                alert('success');
            },
            error: function (jqxhr, textStatus, error) {
                alert('fail');
            }
        });

Action Method :

<HttpPost>
        <Route("Data")>
        Function GetData(ByVal IsInit As Boolean, ByVal SearchParam As Newtonsoft.Json.Linq.JObject) As ActionResult
            Return Nothing
        End Function

Now, above action doesn't call at all. but if you use below code then it makes the call but SearchParam is of type [object] only and you can not use any value of searchParam object.

<HttpPost>
    <Route("Data")>
    Public Function GetData(ByVal IsInit As Boolean, ByVal SearchParam As Object) As Object
        Return Nothing
    End Function

I think that it does not able to pass multiple parameter in POST request with complex json object.

How can i get JSON data passed to MVC controller's action method so that SearchParam Json data converted to JObject it self. i.e. initial first Action method signature should be used with out any major method signature changes.

Few Observation :

  1. if i turned above action method as api in API Controller; it start working but having said that you need to follow the below method signature. below approach is not working for MVC controller. Don't know why ?? However, For Some reason; i can not go with API controller.

        <HttpPost>
        <Route("Data")>
        Function GetData(ByVal req As Newtonsoft.Json.Linq.JObject) As ActionResult
            Return Nothing
        End Function
    

Thanks !!


Solution

  • Better to never use JOBject for this. Instead it is much more practical and highly recommended to create and use a Model class. MVC Web API will then bind the incoming JSON to a Model object, all for free.

    Example:

    Public Class MyData
        Public Property IsInit As Boolean
        Public Property Type As String
        Public Property Name As String
        Public Property Sort As String
    End Class
    

    Note that here I piled everything into one Class. If you want to keep the IsInit separate from the rest then you can split it like this:

    Public Class Param
        Public Property Type As String
        Public Property Name As String
        Public Property Sort As String
    End Class
    
    Public Class MyData
        Public Property IsInit As Boolean
        Public Property SearchParam as Param
    End Class
    

    Then change your Action Method like this:

    Function GetData(<FromBody()> ByVal data As MyData) As ActionResult
        ...
    End Function
    

    Finally you probably need to use data: json in your call, so without calling JSON.stringify().