2013-01-14 40 views
0

我正在使用MVC ASP创建一系列由SQL存储过程填充的dropdownlist。但是,每个连续的下拉列表需要通过将前一个列表的选择作为参数传递给过程调用来填充。我如何可以POST使用创建的列表的选择:C#DropDownList回发

@Html.DropDownListFor(x => x.environmentName, new SelectList(Model.environmentName)) 

我试图将它保存到一个modelView,然后再次将视图传递给控制器​​,但我觉得这是一个糟糕的方式去做。

+0

结帐这个例子中[级联的DropDownList在ASP.Net MVC(http://blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net -mvc.aspx) –

+0

这是使用jQuery完成它的一个很好的例子,但是我也需要每次运行存储的proc,并将列表中选定的值作为参数传递。在那个例子中,他只是在创建时初始化json对象。 –

回答

0

这里是我为3个级联下拉式AJAX回调写的JQuery解决方案,控制器根据之前的选择填充下一个列表。这可能会让你朝着正确的方向前进。

Select: <select id="category" style="width: 150px"> 
     <option></option> 
     @foreach (string cat in ViewBag.Categories) 
     { 
      <option>@cat</option> 
     } 
    </select><span id="errorforcategory" style="color: red"></span> 
<select id="subcategory1" disabled="disabled" style="width: 150px"><option></option>  </select> 
<select id="subcategory2" disabled="disabled" style="width: 150px"><option></option></select> 


<script type="text/javascript"> 
$("#category").change(function() { 
    $("#subcategory1").load('@Url.Action("GetSubCategory")' + "?category=" +  $("#category").val()); 
    $('#subcategory2').empty(); 
    $('#subcategory2').append($("<option></option>")); 
    $('#subcategory2').attr('disabled', 'disabled'); 
}).ajaxStop(function() { 
    if ($('#subcategory1 option').size() > 2) { 
     $('#subcategory1').attr('disabled', ''); 
    } else { 
     $('#subcategory1').attr('disabled', 'disabled'); 
    } 

}); 

$("#subcategory1").change(function() { 
    if ($("#subcategory1").val().trim()) { 
     $("#subcategory2").load('@Url.Action("GetSubCategory")' + "?category=" + $("#category").val() + "&subcategory=" + $("#subcategory1").val()); 
    } else { 
     $('#subcategory2').empty(); 
     $('#subcategory2').attr('disabled', 'disabled'); 
    } 
}).ajaxStop(function() { 
    if ($('#subcategory2 option').size() > 2) { 
     $('#subcategory2').attr('disabled', ''); 
    } else { 
     $('#subcategory2').attr('disabled', 'disabled'); 
    } 
}); 

然后在你的控制器,你可以你的存储过程使用任何方法,你喜欢,然后打造出你的结果选项的文本调用。

public string GetSubCategory(string category, string subcategory) 
    { 
     string returnval = "<option></option>"; 
     if (!string.IsNullOrEmpty(subcategory)) 
     { 
      foreach (
       var cat in 
        db.Categories.Where(c => c.category1 == category && c.subcategory1 == subcategory) 
         .Select(c => c.subcategory2) 
         .Distinct()) 
      { 
       if (!string.IsNullOrEmpty(cat.Trim())) 
        returnval += "<option>" + cat + "</option>"; 
      } 
      return returnval; 
     } 

     return Enumerable.Aggregate(db.Categories.Where(c => c.category1 == category).Select(c => c.subcategory1).Distinct().Where(cat => !string.IsNullOrEmpty(cat.Trim())), returnval, (current, cat) => current + ("<option>" + cat + "</option>")); 
    }