我必须从视图页面向控制器发送一个对象。
Ajax代码: -
var jsdata = '{p:' + data + '}';
$.ajax({
type: "POST",
url: rootURL + "Deal/Check",
contentType: 'application/json; charset=utf-8',
data:JSON.stringify(jsdata, null, 2) ,
success: function (data) {}
});
控制器: -
[HttpPost]
public async Task<ActionResult> Check(DealCreateViewModel p)
{
CheckAvailabilities(p);
return View();
}
DealCreateViewModel: -
public List<AllocationID> Titles { get; set; }
public List<AllocationID> Episodes { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Assets { get; set; }
[UIHint("MultiPicker")] public List<QuickID> Documents { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Languages { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Territories { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Countries { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Rights { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Contributors { get; set; }
[UIHint("MultiPicker")] public List<AllocationID> Transmissions { get; set; }
我通过ajax发送的对象“数据”可以是任何意思,它可以是资产列表,标题列表,剧集列表或Viewmodel中的任何其他内容。
答案 0 :(得分:0)
尝试以下代码
$.ajax({
type: "POST",
url: rootURL + "Deal/Check",
contentType: 'application/json; charset=utf-8',
dataType:'json',
data: { p : data },
success: function (data) {}
});
答案 1 :(得分:0)
您可以将其作为简单的json字符串发送。但是,您不会知道对象的类型或对象的类。所以我们必须指定类型以及我们传递给action方法的json字符串。在您的情况下,您需要指定列表类型(AllocationID,QuickID)和对象类(文档,位置等)。
因此样本json看起来像:
var jsdata = {
"listType": "AllocationID",
"objectName" : "Documents",
"data": [
//list of json object representing a document.
]
};
var dto = { jsonData: jsData };
$.ajax({
type: "POST",
url: rootURL + "Deal/Check",
data:JSON.stringify(dto),
success: function (data) {}
});
您的操作方法如下:
[HttpPost]
public async Task<ActionResult> Check(string jsonData)
{
//use newtonsoft json parser
JObject obj = JObject.Parse(jsonData);
var listType = obj["listType"].Value<string>();
if(listType == 'AllocationID')
{
var jarr = obj["data"].Value<JArray>();
List<AllocationID> documents = jarr.ToObject<List<AllocationID>>();
//do something with documents list...
}
}