2012-09-05 18 views
0

我有一個下拉列表,當它改變。我想選擇的值進入控制器使用AJAX下拉列表與Ajax不會去控制器

 $(document).ready(function() { 
     $("#otherCatches").change(function() { 

      $.ajax({ 
       url: "Clients/DDL", 
       type: "POST", 
       data: { 
        name: $('#othercatches').val() 
       }, 
       success: function (result) { 
        alert(result) 
       } 
      }); 
      return false; 
     }); 
    }); 

     <select id ="otherCatches"> 
      @foreach (var item in Model.Sample) 
     { 
      <option> 
       @item.SampleName 
      </option> 
     } 
     </select> 

它不打控制器

[HttpPost] 
public virtual ActionResult DDL(int name) 
{ 

    //do method here 

} 

回答

1

在您的視圖代碼中,你是不是設置optionvalue屬性。所以$('#othercatches').val()會給你undefined

使用DropDownList/DropDownListForHTML幫助器方法呈現SELECT元素。

使用強類型視圖。例如:如果你的觀點是創建DDL,您將定義一個視圖模型這樣

public class ClientDDL 
{ 
    public string Name { set;get;} 
    public int SelectedCatch { set;get;} 
    public IEnumerable<SelectListItem> OtherCatches { set;get;} 
    //Other relevant proeprties also here 

    public ClientDDL() 
    { 
    //Lets initialize the OtherCatches Proeprty 
     OtherCatches=new List<SelectListItem>(); 
    } 
} 

現在我們GET行動,我們將創建這個視圖模型的對象,發送到視圖。現在

public ActionResult CreateDDL() 
{ 
    ClientDDL ddl new ClientDDL(); 

    // The below line is hard coded for demo. you may replace 
    // this with loading data from your Data access layer. 
    ddl.OtherCatches= new[] 
    { 
      new SelectListItem { Value = "1", Text = "Book" }, 
      new SelectListItem { Value = "2", Text = "Pen" }, 
      new SelectListItem { Value = "3", Text = "Computer" } 
    };   
    return View(ddl); 
} 

我們認爲(CreateDDL.cshtml),這是強類型我們ClientDDL類看起來像這樣

@model ClientDDL  
@using(Html.Beginform()) 
{ 
    @Html.DropDownListFor(x => x.SelectedCatch, 
        new SelectList(Model.OtherCatches,"Value","Text"), "Select..") 

} 
<script type="text/javascript">  
    $(function(){ 
     $("#SelectedCatch").change(function(){ 
      $.ajax({ 
      url: "@Url.Action("DDL","Clients")", 
      type: "POST", 
      data: { name: $(this).val() }, 
      success: function (result) { 
       alert(result) 
      } 
      }); 
     }); 
    }); 
</script> 

決不硬編碼路徑,這樣的操作方法。儘可能使用URL Helper方法。

不確定爲什麼你有一個virtual方法?它應該很簡單,因爲這

[HttpPost] 
public ActionResult DDL(int name) 
{ 

    //do method here 

} 
+0

感謝上例的示例代碼我的朋友 –