2013-08-24 105 views
0

我對MVC非常陌生,並試圖使用this example設置一系列級聯下拉列表。如何從級聯下拉列表中獲取值使用ajax

但是我被卡住了一點,因爲我不知道如何從第二個下拉列表中獲取值並將其發送到控制器,當我按下相應的按鈕時。

這是我的觀點:

<script type="text/javascript"> 
    $('#list').change(function() { 
     var selectedClient = $(this).val(); 
     if (selectedClient != null && selectedClient != '') { 
      $.getJSON('@Url.Action("SelectC")', { clientID: selectedClient }, function (client) { 
       var campaingSelect = $('#clist'); 
       campaingSelect.empty(); 
       $.each(client, function(index, clients) { 
        campaingSelect.append($('<option/>', { 
         value: clients.value, 
         text: clients.text 
        })); 
       }); 
      }); 
     } 
    }); 
</script> 
@using (Html.BeginForm("CreateNewCampaign", "Home", FormMethod.Post)) 
{ 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    @Html.LabelFor(m => m.alreadyCreatedCampaignName, "Name:") 
    @Html.DropDownList("clist","-- Select Client -2-") 
    <input type="Submit" name="button" value="Select" class="btn btn-primary" /> 
} 

控制器:

public ActionResult SelectC(int clientId, CampaignModel model, FormCollection form) 
     { 
      Session["ClientID"] = clientId; 

      ViewBag.ClientName = "You're using: " + Session["ClientName"]; 

      var CampaignInf = CampaignManagementService.GetCampaigns((string) Session["ticket"], clientId); 
      List<AlreadyCreatedCampaignList> itemas = new List<AlreadyCreatedCampaignList>(); 
      foreach (var element in CampaignInf) 
      { 
       itemas.Add(new AlreadyCreatedCampaignList() {CampId = element.Key, CampName = element.Value}); 
      } 

      var listOfCam = new SelectList(itemas, "campID", "campName", 1); 
      return Json(listOfCam.Select(x => new {value = x.Value, text = x.Text}), JsonRequestBehavior.AllowGet); 
     } 

我想要得到的值到其他控制器,並且我不知道的正確的方式去這樣做。

+0

的問題並不是那麼清楚,哪裏是要根據第一個下拉篩選第二個下拉按鈕。 – Sravan

+0

Button is here @ Html.DropDownList(「clist」,「 - Select Client -2-」) 通過篩選一切正常,但如何從其他下拉菜單中獲取價值並將其傳輸到控制器 – piotr

回答

0

你可以通過給它ID並調用$("#id").val();來獲得dropdownlist的值,然後你可以通過ajax將它傳遞給控制器​​。

這裏是我的,試試吧
public ActionResult ActionName(string dropdown_value){ //your code }

<script> 
$(document).ready(function(){ 
$("submit").click(function(){ 
$.ajax({ 
    url:"Controller/ActionName", 
    datatype: "POST", 
    data: { dropdown_value : $("#clist").val() }, 
    success : function(){ //your code if success } 
}); 
}); 
}); 
</script>