2013-04-03 40 views
19

我的控制器:邮政JavaScript数组与AJAX到ASP.NET MVC控制器

[HttpPost] 
public ActionResult AddUsers(int projectId, int[] useraccountIds) 
{ 
    ... 
} 

我想参数发布到通过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.'); 
     } 
    }); 
} 

我与测试数组,但没有成功尝试。 :( 我也试着设置traditional: true,或contentType: 'application/json; charset=utf-8'但没有成功,以及...

int[] useraccountIds贴到我的控制器总是空

+0

请发布错误消息 – Mortalus

+0

我已经调试了控制器方法,并且int [] useraccounts始终为空。 – mosquito87

+0

总是最好查看发送的实际数据。要么获取Fiddler,要么查看网络下的开发人员工具(即Firefox/Firebug的Chrome)。 – samjudson

回答

34

你可以定义一个视图模型:

public class AddUserViewModel 
{ 
    public int ProjectId { get; set; } 
    public int[] userAccountIds { get; set; } 
} 

然后适应您的控制器动作借此视图模型作为参数:

[HttpPost] 
public ActionResult AddUsers(AddUserViewModel model) 
{ 
    ... 
} 

最后调用它:

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.'); 
     } 
    }); 
} 
+0

即使是硬编码的projectId(如23)也不会发送到控制器。 而是发送真实的表单数据(还有一个项目ID)。 :( – mosquito87

+1

这个'sendForm'函数在那里,你在哪里调用它?它是在某个表单的提交事件还是某个提交按钮的点击事件?你确定通过返回false来取消该事件的默认操作我想你没有。 –

+0

是的,你是完全正确的。什么愚蠢的错误。我很抱歉... – mosquito87

0

如果你想传递数组到mvc引擎,多次发送输入。更改您的代码如下:

function sendForm(projectId, target) { 
var useraccountIds = new Array(1, 2, 3); 
var data = { projectId: projectId }; 
for (var i = 0; i < useraccountIds.length; i++) { 
    $.extend(true, data, {useraccountIds: useraccountIds[i]}); 
} 
$.ajax({ 
    traditional: true, 
    url: target, 
    type: "POST", 
    data: data, 
    success: ajaxOnSuccess, 
    error: function (jqXHR, exception) { 
     alert('Error message.'); 
    } 
}); 

}

+0

根据firebug中的网络监视器,AJAX发送的数据确实在表单中,但不是我用数据指定的数据... – mosquito87

+0

是的,我找到了解决方案,并且编辑了我的答案,但是我的代码没有经过测试,但是这是解决方案 – Rabolf

0

把Serializable属性的类。然后它会尝试将您传递给C#类的JavaScript对象转换。

在JS:

{ 
    ProjectId = 0, 
    userAccountIds = [] 
} 

// C# 
[Serializable] 
public class AddUserViewModel 
{ 
    public int ProjectId { get; set; } 
    public int[] userAccountIds { get; set; } 
} 
+0

这个工作没有viewmodel吗? – mosquito87

+0

是的,具有Seri​​alizable属性的普通类就足够了。 – marko

2

使用$。阿贾克斯(),您可以轻松地从JavaScript中的数据得到MVC中的控制器。

作为等,

var uname = 'John Doe'; 

$.ajax({ 

     url: "/Main/getRequestID", // This is path of your Controller with Action Result. 
     dataType: "json",   // Data Type for sending the data 

     data: {      // Data that will be passed to Controller 
      'my_name': uname,  // assign data like key-value pair  
      // 'my_name' like fields in quote is same with parameter in action Result 
     }, 

     type: "POST",    // Type of Request 
     contentType: "application/json; charset=utf-8", //Optional to specify Content Type. 

     success: function (data) { // This function is executed when this request is succeed. 
       alert(data); 
     }, 

     error: function (data) { 
       alert("Error"); // This function is executed when error occurred. 
     } 
)}; 

然后,在控制器侧,

public ActionResult getRequestID(String my_name) 
{ 

    MYDBModel myTable = new Models.MYDBModel(); 
    myTable.FBUserName = my_name; 
    db.MYDBModel.Add(myTable); 
    db.SaveChanges();    // db object of our DbContext.cs 
    //return RedirectToAction(“Index”); // After that you can redirect to some pages… 
    return Json(true, JsonRequestBehavior.AllowGet); // Or you can get that data back after inserting into database.. This json displays all the details to our view as well. 
} 

参考。 Send Data from Java Script to Controller in MVC

+0

链接已损坏。 – JoshYates1980

+0

谢谢乔希更新我.. 我已更新链接。请检查。其实我已经把我的博客从Wordpress转移到博主。所以这个链接被打破了。现在它的工作.. –

14

在JS:

var myArray = new Array(); 
myArray.push(2); 
myArray.push(3); 
$.ajax({ 
      type: "POST", 
      url: '/MyController/MyAction', 
      data: { 'myArray': myArray.join() }, 
      success: refreshPage 
     }); 

在MVC中/ C#:

public PartialViewResult MyAction(string myArray) 
{ 
    var myArrayInt = myArray.Split(',').Select(x=>Int32.Parse(x)).ToArray(); 
    //My Action Code Here 
} 
0

,除非你指定它不会工作的Ajax请求(邮政/ GET)有属性 traditional设置为true。 有关更多详情,请参阅此question

相关问题