我正在尝试使用一个对象数组传递给MVC控制器方法 jQuery的ajax()函数。当我进入PassThing()C#控制器方法时, 参数“things”为null。我已经尝试使用一种List for 这个论点,但这也不起作用。我做错了什么?
<script type="text/javascript">
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Xhr/ThingController/PassThing',
data: JSON.stringify(things)
});
});
</script>
public class ThingController : Controller
{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
答案 0 :(得分:164)
使用NickW的建议,我能够使用things = JSON.stringify({ 'things': things });
来完成这项工作。这是完整的代码。
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
我从中学到了两件事:
在ajax()函数中绝对需要contentType和dataType设置。如果它们丢失,它将无法工作。经过多次试验和错误,我发现了这一点。
要将对象数组传递给MVC控制器方法,只需使用JSON.stringify({'things':things})格式。
我希望这有助于其他人!
答案 1 :(得分:28)
难道你不能这样做吗?
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
function () {
$('#result').html('"PassThings()" successfully called.');
});
...并用
标记您的行动[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
// do stuff with things here...
}
答案 2 :(得分:12)
格式化可能存在问题的数据。尝试以下任何一种:
data: '{ "things":' + JSON.stringify(things) + '}',
或(来自How can I post an array of string to ASP.NET MVC Controller without a form?)
var postData = { things: things };
...
data = postData
答案 3 :(得分:8)
我正在使用.Net Core 2.1 Web应用程序,但无法在此处获得单一答案。我要么得到一个空白参数(如果方法被调用)或500服务器错误。我开始玩各种可能的答案组合,最后得到了一个有效的结果。
在我的情况下,解决方案如下:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
命名内容
data:{content:nodes},// Server error 500
没有contentType =服务器错误500
dataType
不需要,因为它用于响应解码(因此与请求示例无关) List<Thing>
也适用于控制器方法答案 4 :(得分:7)
我能让它工作的唯一方法是将JSON作为字符串传递,然后使用JavaScriptSerializer.Deserialize<T>(string input)
对其进行反序列化,如果它是MVC 4的默认解串译器,那就太奇怪了。
我的模型有嵌套的对象列表,我可以使用JSON数据获得的最佳列表是最上面的列表,其中包含正确的项目数,但项目中的所有字段都为空。
这种事情不应该那么难。
$.ajax({
type: 'POST',
url: '/Agri/Map/SaveSelfValuation',
data: { json: JSON.stringify(model) },
dataType: 'text',
success: function (data) {
[HttpPost]
public JsonResult DoSomething(string json)
{
var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
答案 5 :(得分:6)
我对这一切都有完美的答案:我尝试了很多无法最终自己管理的解决方案,请在下面找到详细解答:
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(
[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]),
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
<强>的Controler 强>
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
答案 6 :(得分:4)
这是您查询的工作代码,您可以使用它。
的Controler
[HttpPost]
public ActionResult save(List<ListName> listObject)
{
//operation return
Json(new { istObject }, JsonRequestBehavior.AllowGet); }
}
的javascript
$("#btnSubmit").click(function () {
var myColumnDefs = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
} else {
myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
}
});
var data1 = { 'listObject': myColumnDefs};
var data = JSON.stringify(data1)
$.ajax({
type: 'post',
url: '/Controller/action',
data:data ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
答案 7 :(得分:1)
var List = @Html.Raw(Json.Encode(Model));
$.ajax({
type: 'post',
url: '/Controller/action',
data:JSON.stringify({ 'item': List}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
答案 8 :(得分:0)
如果您使用的是ASP.NET Web API,那么您应该只传递data: JSON.stringify(things)
。
你的控制器应该是这样的:
public class PassThingsController : ApiController
{
public HttpResponseMessage Post(List<Thing> things)
{
// code
}
}
答案 9 :(得分:0)
来自@veeresh i的修改
var data=[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]; //parameter
var para={};
para.datav=data; //datav from View
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:para,
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
In MVC
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
答案 10 :(得分:0)
使用包含与MVC控制器所需参数名称相匹配的属性的另一个对象来包装对象列表。 重要的一点是对象列表的包装。
$(document).ready(function () {
var employeeList = [
{ id: 1, name: 'Bob' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Tom' }
];
var Employees = {
EmployeeList: employeeList
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Employees/Process',
data: Employees,
success: function () {
$('#InfoPanel').html('It worked!');
},
failure: function (response) {
$('#InfoPanel').html(response);
}
});
});
public void Process(List<Employee> EmployeeList)
{
var emps = EmployeeList;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
答案 11 :(得分:0)
当我尝试从DataTable中的几个选定行发送一些数据到MVC操作时,我做了什么:
HTML 在页面的开头:
@Html.AntiForgeryToken()
(仅显示一行,从模型绑定):
@foreach (var item in Model.ListOrderLines)
{
<tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
<td>@item.OrderId</td>
<td>@item.OrderDate</td>
<td>@item.RequestedDeliveryDate</td>
<td>@item.ProductName</td>
<td>@item.Ident</td>
<td>@item.CompanyName</td>
<td>@item.DepartmentName</td>
<td>@item.ProdAlias</td>
<td>@item.ProducerName</td>
<td>@item.ProductionInfo</td>
</tr>
}
启动JavaScript功能的按钮:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript函数:
function ProcessMultipleRows() {
if ($(".dataTables_scrollBody>tr.selected").length > 0) {
var list = [];
$(".dataTables_scrollBody>tr.selected").each(function (e) {
var element = $(this);
var orderid = element.data("orderid");
var iscustom = element.data("iscustom");
var orderlineid = element.data("orderlineid");
var folderPath = "";
var fileName = "";
list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
});
$.ajax({
url: '@Url.Action("StartWorkflow","OrderLines")',
type: "post", //<------------- this is important
data: { model: list }, //<------------- this is important
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
showPreloader();
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function () {
hidePreloader();
}
});
}
}
MVC操作:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
还有C#中的MODEL:
public class WorkflowModel
{
public int OrderId { get; set; }
public int OrderLineId { get; set; }
public bool IsCustomOrderLine { get; set; }
public string FolderPath { get; set; }
public string FileName { get; set; }
}
结论:
错误原因:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
是属性:[ValidateAntiForgeryToken]
用于MVC操作StartWorkflow
Ajax调用中的解决方案:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
要发送对象列表,您需要形成数据,例如示例(填充列表对象)和:
数据:{型号:列表},
类型:“帖子”,
答案 12 :(得分:0)
这对我来说很好:
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
ContentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Controller/action',
data: { "things": things },
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
error: function (response) {
$('#result').html(response);
}
});
大写字母“ C”中带有“ ContentType”。
答案 13 :(得分:0)
删除 contentType
在 asp.net core 3.1 中对我有用
所有其他方法都失败
答案 14 :(得分:0)
我可以确认在 asp.net core 2.1 上,删除内容类型使我的 ajax 调用正常工作。
function PostData() {
var answer = [];
for (let i = 0; i < @questionCount; i++) {
answer[i] = $(`#FeedbackAnswer${i}`).dxForm("instance").option("formData");
}
var answerList = { answers: answer }
$.ajax({
type: "POST",
url: "/FeedbackUserAnswer/SubmitForm",
data: answerList ,
dataType: 'json',
error: function (xhr, status, error) { },
success: function (response) { }
});
}
[HttpPost]
public IActionResult SubmitForm(List<Feedback_Question> answers)
{}