[英]How to pass a tuple from javascript to ASP.NET MVC controller action
I have below tuple in javascript that I use to group some kind of data:我在 javascript 中有以下元组,用于对某种数据进行分组:
var myTuple = {
item1 : value1,
item2 : value2,
item3 : value3
};
Now I want to pass it to an ASP.NET MVC controller action as the last parameter.现在我想将它作为最后一个参数传递给 ASP.NET MVC 控制器操作。 This ASP.NET MVC controller action already has a lot of parameters passed.
这个 ASP.NET MVC 控制器操作已经传递了很多参数。 I am using an ajax call like below:
我正在使用如下所示的 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
},
});
How can I do it?我该怎么做? Or is there any other better way to do it?
或者有没有其他更好的方法来做到这一点?
In my opinion, with so many parameters being passed it's better to create an object.在我看来,传递了这么多参数,最好创建一个对象。 So your controller should expect just one object - I often make a request model that suits my needs.
所以你的控制器应该只需要一个对象——我经常制作一个适合我需要的请求模型。 This model would contain an object that matches the structure of what's in your Tuple.
该模型将包含一个与元组中的结构相匹配的对象。
On your JS end I would create a similar object to your model and instead of putting it into your url like that I would put it as part of the data
of the call since you already say you're sending json
and the type is post
:在您的 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
},
});
Of course if you need to keep some of those in the query string that would work too.当然,如果您需要在查询字符串中保留一些也可以使用。
EDIT: Example as requested编辑:按要求示例
Your JS could look something like this:你的 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
},
});
Your C# could look something like this:您的 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; }
}
Note that it's important to match the structure of the object your Action is expecting with the object you are sending.请注意,将 Action 期望的对象的结构与您发送的对象相匹配很重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.