Reputation: 61
How do I get the JSON data in my controller, when I dont know the JSON object name? The Json object in my case is an array of objects, which have known property names.
For instance, if I had a black box page, posting JSON to my controller, and I didnt know the Json object name at the top level, e.g. in the example below if "RandomName" could be anything.
<div>
<input type="button" value="click1" id="click1" />
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#click1').click(function (e) {
//alert('here');
var jsonObject = {
"RandomName": [{ "WidgetName": "Cog", "Description": "Blah Blah" }, { "WidgetName": "Bolt", "Description": "Nuts and Bolts" }]
};
$.ajax({
url: "@Url.Action("DoSomething")",
type: "POST",
data: JSON.stringify(jsonObject),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response.responseText);
},
success: function (response) {
alert(response);
}
});
});
});
</script>
..and I had the following class, which defines my data structure:
public class MyModel
{
public List<Widget> widget { get; set; }
}
public class Widget
{
public string WidgetName { get; set; }
public string Description { get; set; }
}
What do I define as a parameter to my controller, when MyModel has a property widget, but I dont know the name given by the client. Its some random name.
[HttpPost]
public ActionResult DoSomething(MyModel model)
{
return Json("Success");
}
Upvotes: 0
Views: 382
Reputation: 1039100
Before stringifying, massage your object and instead of:
data: JSON.stringify(jsonObject)
use:
data: JSON.stringify(jsonObject[Object.keys(jsonObject)[0]]) // get rid of the root property
Now the request will look like this:
[{
"WidgetName": "Cog",
"Description": "Blah Blah"
}, {
"WidgetName": "Bolt",
"Description": "Nuts and Bolts"
}]
and your controller action can now directly take a List<Widget>
parameter.
Obviously this assumes that your jsonObject
will always have 1 property (whose name you do not control as it probably comes from some other source).
Upvotes: 1