MVC4 - 渲染html.dropdownlist

时间:2012-10-30 12:12:47

标签: asp.net-mvc

我想渲染一个html.dropdownlist,以便用户只需“点击”一个项目,在默认渲染中,用户必须点击下拉列表,然后列表将出现,然后上帝可以选择一个项目。

我想把它显示为ul \ li列表,但不知道如何,我确定我可以做一些css的东西,但如何将选定的SelectListItem-Value重新放回数据源...... ?我很确定那里已经有了一些东西。有人能指出我正确的方向吗?

祝你好运, Jurjen。

1 个答案:

答案 0 :(得分:2)

让我们为您的屏幕创建一些视图模型。假设我们正在进行商店定位器视图,其中用户必须从下拉列表中选择状态,然后我们将在单选按钮中显示属于该状态的商店。

public class LocateStore
{
  public List<SelectListItem> States { set;get;}
  public int SelectedState { set;get;}
  public LocateStore()
  {
     States=new List<SelectListItem>();
  }
}
public class StoreLocation
{
  public List<Store> Stores{ set;get;}
  public int SelectedStore { set;get;}
  public StoreLocation()
  {
     Stores=new List<Store>();
  } 
}
public class Store
{
  public int ID { set;get;}
  public string Name { set;get;}
}

现在在GET操作中,创建LocateStore类的对象并设置State集合属性值并将其发送到视图。

public ActionResult Locate()
{
  var vm=new LocateStore();
  //The below code is hardcoded for demo. you mat replace with DB data.
  vm.States= new List<SelectListItem>
  {
    new SelectListItem { Value = 1, Text = "MI" },
    new SelectListItem { Value = 2, Text = "CA" },
    new SelectListItem { Value = 3, Text = "OH" }
  };  
  return View(vm);
}

现在创建一个强类型为LocateStore类的Locate视图。我们将有一些javascript代码来监听下拉列表的更改事件,并进行ajax调用以获取单选按钮列表视图。

@model LocateStore
@Html.DropDownListFor(x=>x.SelectedState, 
                    new SelectList(Model.States,"Value","Text"),"Please select")
<div id="stores">

</div>
<script type="text/javascript">
   $(function(){
     $("#SelectedState").change(function(){
        $("#stores").load("@Url.Action("GetStores","Store")/"+$(this).val());
     });
   });
</script>

现在我们需要一个GetStores操作方法,它接受所选的状态ID并返回一个部分视图,该视图具有以单选按钮列表格式存储的名称。

public ActionResult GetStores(int id)
{
     var vm=new StoreLocation();
      //The below code is hardcoded for demo. you mat replace with DB data.
      vm.Stores= new List<Store>
      {
        new Store{ ID= 1, Name= "Costco" },
        new Store{ ID= 2, Name= "RiteAid" },
        new Store{ ID= 3, Name= "Target" }
      };  
      return PartialView(vm);
}

现在我们需要一个这个方法的视图GetStores.cshtml强烈输入StoreLocation

@model StoreLocation
@foreach(var item in Model.Stores)
{
  @Html.RadioButtonFor(b=>b.SelectedStore,item.ID)  @item.Name
}

现在,当您运行应用程序时,当用户从下拉列表中选择一个项目时,它将带来具有单选按钮的局部视图。

Here是一个使用上述代码的工作示例供您参考。