我在 javascript 中有以下元组,用于对某种数据进行分组:
var myTuple = {
item1 : value1,
item2 : value2,
item3 : value3
};
现在我想将它作为最后一个参数传递给 ASP.NET MVC Controller 操作。此 ASP.NET MVC Controller 操作已经传递了很多参数。我正在使用如下 ajax 调用:
$.ajax({
url: '@Url.Action("MyActionController", "MyController")?Param1=' + $('#Object1').val() + '&Param2=' + param2 + '¶m3=' + param3 + ... + '¶m10=' + param10 + '¶m11=' + myTuple,
type : "POST",
async: false,
dataaType: "JSON",
success: function (result) {
// my stuff
},
});
我该怎么做?或者还有其他更好的方法吗?
最佳答案
在我看来,传递这么多参数最好创建一个对象。因此,您的 Controller 应该只期望一个对象 - 我经常创建一个适合我的需求的请求模型。该模型将包含一个与元组中的结构相匹配的对象。
在你的 JS 端,我会创建一个与你的模型类似的对象,而不是像那样将它放入你的 url 中,我会将它作为调用的 data
的一部分,因为你已经说过了正在发送 json
,类型为 post
:
$.ajax({
url: '@Url.Action("MyActionController", "MyController"),
type : "POST",
data: yourRequestObject, //contains the Tuple
async: false,
dataType: "json",
success: function (result) {
// my stuff
},
});
当然,如果您需要在查询字符串中保留其中一些内容,也可以。
编辑:根据要求示例
你的 JS 可能看起来像这样:
let tuple = {
Item1 : value1,
Item2 : value2,
Item3 : value3
};
let requestObject = {
SomeThing : someValue,
MyTuple : tuple
};
$.ajax({
url: '@Url.Action("MyActionController", "MyController"),
type : "POST",
data: requestObject,
async: false,
contentType: 'application/json',
dataType: "json",
success: function (result) {
// my stuff
},
});
您的 C# 可能如下所示:
public ActionResult MyActionController(MyRequestModel request)
{
// Your Tuple would be accessible here via request.MyTuple
// Do stuff
// ...
return View();
}
public class MyRequestModel
{
public string SomeThing { get; set; }
public MyTuple MyTuple { get; set; }
}
public class MyTuple
{
public string Item1 { get; set; }
public string Item2 { get; set; }
public string Item3 { get; set; }
}
请注意,将您的操作期望的对象结构与您正在发送的对象相匹配非常重要。
关于javascript - 如何将元组从 javascript 传递到 ASP.NET MVC Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60194790/