How to get a dynamically created Json data set in MVC 3 controller?

后端 未结 3 818
北海茫月
北海茫月 2021-01-03 13:14

Ok, so I am using MVC 3 and it is great at de-serializing a JSON data set into a strongly typed object that is passed to my controller action. Unfortunately I have not found

相关标签:
3条回答
  • 2021-01-03 13:24

    There's another option which i prefer using for being neater...(we eliminate the step of getting data from the request stream)

    Here's a code sample

    Cat catObj = new Cat();
    
    if (TryUpdateModel<Cat>(catObj))
    {
    //do stuff
    }
    else
    {
    //invalid input
    }
    

    The TryUpdateModel resides in the controller namespace and hence no need to add any additional reference.

    If you just need the Json sent in as part of the request you could obtain it using the following block of code(you could also obtain it from Request.Form)

    using (StreamReader reader = new StreamReader(Request.InputStream))
    {
        var inputJson = reader.ReadToEnd();
    }
    
    0 讨论(0)
  • 2021-01-03 13:32

    You Could Use JavaScriptSerializer or DataContractSerializer with Some ActionFilters. They're very flexible

    0 讨论(0)
  • 2021-01-03 13:43

    See my answer Passing dynamic json object to C# MVC controller basically using a dynamic type and a ValueProviderFactory is the cleanest way to deserialize Json to something more dynamic.

    0 讨论(0)
提交回复
热议问题