2012-03-12 95 views
-2

我需要在我的MVC3項目中開發兩個下拉列表,其中第一個下拉列表將由數據庫驅動,並基於第一個下拉列表中選擇的數據,我的第二個下拉列表應該更改。第二個下拉菜單是硬編碼文本和值。我怎麼能夠實現這一點。請幫助靜態數據級聯下拉列表

Following is my codebased 

viewmodel 

public IEnumerable<SelectListItem> ProductTypeCode{ get; set; } 
public int? ProductID { get; set; } 


public IEnumerable<SelectListItem> ProductGroupCode; 
public int? ProductGrpID { get; set; } 

Controller 

public ActionResult Index()  {   
var model = new MyViewModel   
{    
// TODO: Fetch those from your repository , 
model.ProductTypeCode= new SelectList(obj.ProductTypeCode as     System.Collections.IEnumerable, "Value", "DispalyText"); 
return view(model); 

} 

VIEW 


@Html.DropDownListFor(m => m.ProductID , Model.ProductTypeCode, "ALL" , new { @class = "DropDownList" })</td> 

我的問題是基於productType上述下拉列表中,我需要填充稱爲「ProductGroup」,這是有硬編碼值另一個下拉。基於ProductType下拉菜單,產品組的值應該改變。

+0

你應該分享你已經試過的東西,比如示例代碼。否則,沒有人知道在哪裏可以真正指引你到更多的在線參考。有關更詳細的幫助和解決問題的方法,請提供示例。 – RogueSpear00 2012-03-12 18:50:05

+0

你有任何可以提供的代碼嗎? – 2012-03-12 18:51:08

回答

0

你有幾個選項。

  1. 您可以編寫自己的javascript來處理onchange事件。在這個確切的主題上有幾千個簡單的教程。 This one可能會解決您的問題最好的。

  2. 你可以使用extensions like Telerik's.他們是相對直接的,有據可查,但確實有額外的權重的另一個庫(雖然他們產生的標記是相當苗條)。

如果你選擇1並編寫你自己的,你必須添加的兩個主要的東西將是一個額外的控制器動作和一些JavaScript。

JavaScript將偵聽您的產品ID下拉列表中的更改事件。把它放在頁面本身的文檔就緒函數中。

$("#ProductID").change(function() { 

    // Get the product id selected 
    var id = $(this).val(); 

    // Fire off an ajax request to get the groups 
    $.ajax({ 
     // whatever the url may be. 
     url: "@Url.Action("Groups")" + id, // Append the id to the url. 
     dataType: "json", 
     type: "POST", 
     error: function() { 
      alert("An error occurred."); 
     }, 
     success: function(data) { 
      var items = ""; 
      $.each(data, function(i, item) { 
       items += "<option value=\"" + item.Id+ "\">" + item.Name + "</option>"; 
      }); 

      // Set the secondary dropdown content to the newly created 
      // list of options. Use whatever Id your secondary is. 
      $("#ProductGroup").html(items); 
    }); 

控制器操作以相應產品組列表響應ajax調用。

public class ProductsController : Controller 
{ 
    public ActionResult Groups(int id) 
    { 
     // You only need the id and a name field in the response, not the 
     // entire object. 
     var groups = _myService.FindGroupsForProductId(id) 
      .Select(g => new 
      { 
       Id = g.Id, 
       Name = g.Name 
      }); 

     // Return a json result. You only need to re 
     return Json(groups); 
    } 
} 

上面的代碼應該可以幫助您入門。它假定你沒有在你的代碼中展示過幾件事情。你的問題被低估了,因爲起初,你沒有發佈任何代碼。然後,您發佈的代碼並不真正表明您已經付出了自己的努力尋找解決方案。找到一些關於這個jQuery的教程,有成千上萬,然後如果你有具體問題,把它們帶到這裏。