[ACCEPTED]-Passing dynamic json object to C# MVC controller-asp.net-mvc-3
Presumably the action that accepts input 4 is only used for this particular purpose 3 so you could just use the FormCollection
object and then 2 all your json properties of your object 1 will be added to the string collection.
[HttpPost]
public JsonResult JsonAction(FormCollection collection)
{
string id = collection["id"];
return this.Json(null);
}
You can submit JSON and parse it as dynamic 10 if you use a wrapper like so:
JS:
var data = // Build an object, or null, or whatever you're sending back to the server here
var wrapper = { d: data }; // Wrap the object to work around MVC ModelBinder
C#, InputModel:
/// <summary>
/// The JsonDynamicValueProvider supports dynamic for all properties but not the
/// root InputModel.
///
/// Work around this with a dummy wrapper we can reuse across methods.
/// </summary>
public class JsonDynamicWrapper
{
/// <summary>
/// Dynamic json obj will be in d.
///
/// Send to server like:
///
/// { d: data }
/// </summary>
public dynamic d { get; set; }
}
C#, Controller 9 action:
public JsonResult Edit(JsonDynamicWrapper json)
{
dynamic data = json.d; // Get the actual data out of the object
// Do something with it
return Json(null);
}
Annoying to add the wrapper on the 8 JS side, but simple and clean if you can 7 get past it.
Update
You must also switch over to 6 Json.Net as the default JSON parser in order 5 for this to work; in MVC4 for whatever reason 4 they've replaced nearly everything with 3 Json.Net except Controller serialization 2 and deserialization.
It's not very difficult 1 - follow this article: http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/
Another solution is to use a dynamic type 3 in your model. I've written a blog post 2 about how to bind to dynamic types using 1 a ValueProviderFactory http://www.dalsoft.co.uk/blog/index.php/2012/01/10/asp-net-mvc-3-improved-jsonvalueproviderfactory-using-json-net/
Much like the accepted answer of a FormCollection, dynamic 4 objects can also map to arbitrary JSON.
The 3 only caveat is that you need to cast each 2 property as the intended type, or MVC will 1 complain.
Ex, in TS/JS:
var model: any = {};
model.prop1 = "Something";
model.prop2 = "2";
$http.post("someapi/thing", model, [...])
MVC C#:
[Route("someapi/thing")]
[HttpPost]
public object Thing(dynamic input)
{
string prop1 = input["prop1"];
string prop2 = input["prop2"];
int prop2asint = int.Parse(prop2);
return true;
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.