2011-07-14 81 views
1

我有一個複選框列表和下拉列表。我想從dropdownlist傳遞選定的值並將複選框選中到我的MVC3控制器並使用模型綁定。用jQuery發送多個對象到MVC 3控制器

視圖模型的複選框:爲StateViewModel /Views/Home/EditorTemplates/StateViewModel.cshtml

public class StateViewModel 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public bool Checked { get; set; } 
    public IEnumerable<TransitionViewModel> Transitions { get; set; } 
} 

編輯模板:

@model Mcs.Sibs.UI.Web.Models.StateViewModel 

@Html.HiddenFor(x => x.Id) 
@Html.HiddenFor(x => x.Name) 
<div> 
    @Html.CheckBoxFor(x => x.Checked) 
    @Html.LabelFor(x => x.Checked, Model.Name) 
</div> 

我的觀點:

這是將數據發送到控制器
@using (Html.BeginForm("GetSchedules", "Home", FormMethod.Post, new { id = "checkboxFrm" })) 
{ 
    @Html.EditorForModel() 
    <input id="ShowReportScheduleBtn" type="button" value="Show schedule" onclick="ShowReportSchedules()" /> 
} 

按鈕單擊處理程序:

function ShowReportSchedules() { 
    var selectedGenerationId = $('#SelectedGenerationId').val(); 
    var statesData = JSON.stringify($('#checkboxFrm')); 
    var statesData2 = $('#checkboxFrm').serialize(); //I also tried this 

     $.ajax({ 
      type: 'POST', 
      url: '/Home/GetSchedules', 
      data: { "generationId": selectedGenerationId, "states": statesData }, 
      dataType: "json", 
      contentType: 'application/json; charset=utf-8' 
     }); 
}; 

最後,我的控制器:

[HttpPost] 
    public ActionResult GetSchedules(int generationId, IEnumerable<StateViewModel> states) 
    { 
     return View("Index"); 

我不能值傳遞給我的控制器。我設法只傳遞了沒有jQuery的statesData對象,並在我的表單中使用了type="submit"。當我試圖只通過statesData與jQuery和type="button"我在FireBug中收到「無效的JSON基元」錯誤。

當我嘗試傳遞整數+ statesData對象時,IE 9崩潰並且Firefox掛起。

我試過各種解決方案,但沒有成功。

回答

2

嘗試這樣的:

function ShowReportSchedules() { 
    var selectedGenerationId = $('#SelectedGenerationId').val(); 
    $.ajax({ 
     type: 'POST', 
     url: '@Url.Action("getschedules", "home")?generationId=' + selectedGenerationId, 
     data: { states: $('#checkboxFrm').serialize() }, 
     success: function(result) { 
      // Do something with the results 
     } 
    }); 
}; 
+0

好了,現在我沒有得到任何的異常,generationId傳遞給控制器​​,但狀態不是。這是我在郵件中得到的內容: states =%255B0%255D.Id%3D1%26%255B0%255D.Name%3DObrada%26%255B0%255D.Checked%3Dfalse%26%255B1%255D.Id%3D2 %26%255B1%255D.Name%3DVerifikacija%26%255B1%255D.Checked%3Dtrue%26 etc .. –

+0

好吧,我想明白了,如果您從'data'中刪除大括號和參數名稱,它就會起作用。如果它看起來像這樣: data:$('#checkboxFrm')。serialize() 然後它工作(它正確序列化)。我將這個答案標記爲正確的,但有沒有辦法通過jQuery發送多個對象? –

0
var a = $("#a").serialize(); 
var b = $("#b").serialize(); 
var c = $("#c").serialize(); 


$.ajax({ 
      url: '@Url.Content("~/Controller/Method1")', 
      type: 'POST', 
      data: a+b+c, 
      success: function (success) { 
      // do something 
      } 
     }); 

// in Controller 
[HttpPost] 
public ActionResult Method1(abc a, bcd b, xyz c) 
{ 
} 

// where abc, bcd xyz are class 
相關問題