[英]How do I get the JSON data in my MVC controller, when I dont know the JSON object name?
How do I get the JSON data in my controller, when I dont know the JSON object name? 当我不知道JSON对象名称时,如何在控制器中获取JSON数据? The Json object in my case is an array of objects, which have known property names.
在我的案例中,Json对象是具有已知属性名称的对象数组。
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, eg in the example below if "RandomName" could be anything. 例如,如果我有一个黑匣子页面,则将JSON发布到我的控制器,而我不知道顶层的Json对象名称,例如在下面的示例中,如果“ RandomName”可以是任何东西。
<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. 当MyModel具有属性窗口小部件,但我不知道客户端给定的名称时,如何定义为控制器的参数。 Its some random name.
它是一些随机名称。
[HttpPost]
public ActionResult DoSomething(MyModel model)
{
return Json("Success");
}
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. 并且您的控制器操作现在可以直接采用
List<Widget>
参数。
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). 显然,这假设您的
jsonObject
将始终具有1个属性(您无法控制其名称,因为它可能来自其他来源)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.