mos*_*o87 21 javascript ajax asp.net-mvc jquery
我的控制器:
[HttpPost]
public ActionResult AddUsers(int projectId, int[] useraccountIds)
{
...
}
Run Code Online (Sandbox Code Playgroud)
我想通过AJAX将参数发布到控制器.传递int projectId
不是问题,但我无法设法发布int[]
.
我的JavaScript代码:
function sendForm(projectId, target) {
$.ajax({
traditional: true,
url: target,
type: "POST",
data: { projectId: projectId, useraccountIds: new Array(1, 2, 3) },
success: ajaxOnSuccess,
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用测试阵列,但没有成功.:(我也尝试过设置traditional: true
,contentType: 'application/json; charset=utf-8'
但也没有成功......
该int[] useraccountIds
贴到我的控制器总是空.
Dar*_*rov 36
您可以定义视图模型:
public class AddUserViewModel
{
public int ProjectId { get; set; }
public int[] userAccountIds { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后调整您的控制器操作以将此视图模型作为参数:
[HttpPost]
public ActionResult AddUsers(AddUserViewModel model)
{
...
}
Run Code Online (Sandbox Code Playgroud)
最后调用它:
function sendForm(projectId, target) {
$.ajax({
url: target,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
projectId: projectId,
userAccountIds: [1, 2, 3]
}),
success: ajaxOnSuccess,
error: function (jqXHR, exception) {
alert('Error message.');
}
});
}
Run Code Online (Sandbox Code Playgroud)
Den*_*sic 16
在JS中:
var myArray = new Array();
myArray.push(2);
myArray.push(3);
$.ajax({
type: "POST",
url: '/MyController/MyAction',
data: { 'myArray': myArray.join() },
success: refreshPage
});
Run Code Online (Sandbox Code Playgroud)
在MVC/C#中:
public PartialViewResult MyAction(string myArray)
{
var myArrayInt = myArray.Split(',').Select(x=>Int32.Parse(x)).ToArray();
//My Action Code Here
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
56696 次 |
最近记录: |