【问题标题】:MVC4 - render html.dropdownlistMVC4 - 渲染 html.dropdownlist
【发布时间】:2012-10-30 12:12:47
【问题描述】:

我想渲染一个 html.dropdownlist,这样用户就可以“点击”一个项目,在默认渲染中,用户必须点击下拉列表,然后列表会出现,然后用户可以选择一个项目。

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

最好的问候, 尤尔仁。

【问题讨论】:

  • 你想要的是单选按钮。

标签: asp.net-mvc


【解决方案1】:

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

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 类的定位视图。我们将有一些 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 是使用上述代码的工作示例供您参考。

【讨论】:

  • Shyju,感谢您的回复。但是,当我在新的 mvc4 项目中使用它时,您的示例代码不起作用。如果我使用为模型中的同一字段呈现各种单选按钮的部分,它会以我无法选择项目的方式呈现。
  • @Jurjen:有一些语法错误。我修复了这些,甚至上传了一个示例工作项目供您参考。告诉我它有帮助。
猜你喜欢
  • 2014-05-09
  • 2019-01-31
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-09
相关资源
最近更新 更多