asp.net-mvc - 如何从 Ajax 将具有多个值的 json 对象发布到控制器
问题描述
我有这个 Ajax 帖子为单个值工作,但我需要它来处理多个值。我错过了什么?
我已经尝试将公共类“Value”设为 List AND Guid[]。我试图将方法参数调整为 List AND Value[]。不知道还有什么可以尝试的。
Class:
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]Value information)
View JS:
function SubAll() {
var selectedValues = $('#timesheet').DataTable().column(0).checkboxes.selected().toArray();
var instructions = {};
for (var TimeId in selectedValues) {
instructions[TimeId] = { TimeId: selectedValues[TimeId] };
}
var inst = JSON.stringify(instructions);
$.ajax({
url: "/Admin/ApproveAllTimesheets",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: inst,
success: function (result) {
alert(result);
},
error: function (xhr, textStatus) {
if (xhr.status == 401) { alert("Session Expired!"); window.location = "/Account"; }
else {
alert('Content load failed!', "info");
}
}
});
};
如果我通过这个对象发送它可以工作,但我需要像我的 ajax 帖子那样发送多个值。
var指令= {时间ID:“13246578-1234-7894-4562-456789123456”};
更新#1 我通过扩展类找到了一个适合我的结构,现在我只需要弄清楚如何创建正确的对象和数组组合。
New Classes:
public class ValueContainer
{
public List<Value> MasterIds { get; set; }
}
public class Value
{
public Guid TimeId { get; set; }
}
Method:
public IActionResult ApproveAllTimesheets([FromBody]ValueContainer information)
Structure I need now (this works hard coded):
var jsonObject = {
"MasterIds": [{ TimeId: "13246578-1234-7894-4562-456789123450" }, { TimeId: "13246578-1234-7894-4562-456789123451" }, { TimeId: "13246578-1234-7894-4562-456789123452" }]
};
我对这些东西还是新手,但我看到的是 jsonObject 是一个带有键“MasterIds”的对象,相应的值是一个带有键“TimeId”的对象数组......这是一个正确的评估吗? .以及如何在代码中创建它?
解决方案
您需要创建一个对象数组,然后将其设置在容器对象中:
var instructions = []; // an array
for (var i = 0; i < selectedValues.length; i++) {
instructions.push({ TimeId: selectedValues[i] };
}
var Value = {TimeId: instructions}; // creating object with property TimeId as array of guid
var inst = JSON.stringify(Value);
.......
....... your ajax code
并且您的类属性也应该是数组类型:
public Guid[] TimeId { get; set; }
推荐阅读
- html - 字体真棒图标位于文本字段后面
- python-3.x - semaphore_tracker: 似乎有 1 个泄漏的信号量需要在关机时清理 len(cache))
- node.js - 错误:请求的身份验证范围不足。我只想远程运行一个功能
- marklogic - MarkLogic:DHF 4.0.0 加载自定义 REST 模块
- android - 以可扩展性处理和发送实时位置更新给附近的用户
- javascript - $(event.target) 获取我正在触摸的所有元素
- python - 替代=登录python
- javascript - 如何将值传递给事件处理程序并仍然能够在 JavaScript 中删除事件侦听器?
- json - 在位置 0 处出现 JSON 错误(重复)
- javascript - 如何在打字稿中创建自定义数据类型?