2011-08-31 13 views
5

を使用して、ドロップダウンリストを塗りつぶし、私はドロップダウンリストを持っています。が動的ASP .NET MVCかみそりビューでJavaScript/jQueryの

Javascript/jQuery/Ajaxを使用したボタンクリックや別のドロップダウン選択のようなクライアントサイドアクションに応じて、DeviceModelListを動的に埋め込む方法はありますか?あなたは、部分的には、このドロップダウンを外部化でき

答えて

11

@model MyViewModel 
@Html.DropDownListFor(model => model.SelectedDeviceModel, Model.DeviceModelList) 

、あなたのメインビューには、いくつかのコンテナ内に含まれます:

@model MyViewModel 
... 
<div id="ddlcontainer"> 
    @Html.Partial("Foo", Model) 
</div> 
... 

あなたは、いくつかのパラメータを取るコントローラのアクションを持っている可能性があり、その値に基づいて、この部分的なレンダリングを行います。

public ActionResult Foo(string someValue) 
{ 
    MyViewModel model = ... go ahead and fill your view model 
    return PartialView(model); 
} 

Now最後の部分は、何らかのイベントが発生したときにドロップダウンリストをリフレッシュするAJAXリクエストを送信することです。例えば、いくつかの他のDDL変更の値(または何か他のものは、ボタンをクリックするか、何でも)とき:

$(function() { 
    $('#SomeOtherDdlId').change(function() { 
     // when the selection of some other drop down changes 
     // get the new value 
     var value = $(this).val(); 

     // and send it as AJAX request to the newly created action 
     $.ajax({ 
      url: '@Url.Action("foo")', 
      type: 'POST', 
      data: { someValue: value }, 
      success: function(result) { 
       // when the AJAX succeeds refresh the ddl container with 
       // the partial HTML returned by the Foo controller action 
       $('#ddlcontainer').html(result); 
      } 
     }); 
    }); 
}); 

別の可能性としては、JSONを使用してに構成されています。 Fooコントローラアクションは、新しいキー/値コレクションを含むJsonオブジェクトを返すだけで、AJAXリクエストの成功コールバックではドロップダウンリストを更新します。この場合、別の部分に外部化する必要はありません。たとえば:

$(function() { 
    $('#SomeOtherDdlId').change(function() { 
     // when the selection of some other drop down changes 
     // get the new value 
     var value = $(this).val(); 

     // and send it as AJAX request to the newly created action 
     $.ajax({ 
      url: '@Url.Action("foo")', 
      type: 'POST', 
      data: { someValue: value }, 
      success: function(result) { 
       // when the AJAX succeeds refresh the dropdown list with 
       // the JSON values returned from the controller action 
       var selectedDeviceModel = $('#SelectedDeviceModel'); 
       selectedDeviceModel.empty(); 
       $.each(result, function(index, item) { 
        selectedDeviceModel.append(
         $('<option/>', { 
          value: item.value, 
          text: item.text 
         }) 
        ); 
       }); 
      } 
     }); 
    }); 
}); 

、最終的にあなたのFooのコントローラのアクションJSONを返します。

public ActionResult Foo(string someValue) 
{ 
    return Json(new[] { 
     new { value = '1', text = 'text 1' }, 
     new { value = '2', text = 'text 2' }, 
     new { value = '3', text = 'text 3' } 
    }); 
} 

を同様のたとえばあなたがfollowing answerを見てみましょうことがあります。

+0

部分的なものを使って私のために行く方法でした。ありがとう! – link664

+0

@DarinDimitrov私はあなたのソリューションを実装しましたが、別のddlに値を設定したユーザーの選択に基づいて2番目のajaxリクエストを追加しました。私の問題は、2番目のajaxリクエストが発砲していないということです。なぜなのかご存知ですか? – codingNightmares