0

ドロップダウンリストが変更されたときに表示されます。選択した値を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

}
4

1 に答える 1

1

ビューコードでは、のvalue属性を設定していませんoption。だからあなたに未定義$('#othercatches').val()を与えるでしょう。

DropDownList/ DropDownListForHTML Helperメソッドを使用して、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アクションでは、このViewModelのオブジェクトを作成し、それをビューに送信します。

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ヘルパーメソッドを使用してください。

なぜあなたがvirtual方法を持っているのか分かりませんか?このように単純なはずです

[HttpPost]
public ActionResult DDL(int name)
{

     //do method here

}
于 2012-09-05T16:42:10.630 に答える