2011-08-31 113 views
5

在ASP .NET MVC Razor視圖,我有一個下拉列表如下:填充一個下拉列表,使用JavaScript動態/ jQuery的

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

DeviceModelList僅僅是一個的SelectList。

我該如何動態填充DeviceModelList,具體取決於客戶端操作,如按鈕單擊或使用Javascript/jQuery/Ajax的其他下拉選擇?

回答

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); 
} 

現在最後一部分是發送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我已經實現了您的解決方案,但是我已經添加了第二個Ajax請求,因爲基於用戶下拉選擇,另一個ddl會使用值填充。我的問題是第二個Ajax請求沒有被觸發。你知道爲什麼嗎? – codingNightmares