关于下拉列表HtmlDownlistFor的使用

1.定义下拉列表需要的数据

public static List<SelectListItem> GetProList()
{
  List<SelectListItem> items = new List<SelectListItem>
  {
  new SelectListItem { Text = "全部", Value = "0" },
  new SelectListItem { Text = "未上架", Value = "1" },
  new SelectListItem { Text = "已上架", Value = "2" }
  };
  return items;
}

2.在需要使用的地方,将下拉列表数据传递到前台.

ViewBag.ProList= GetProList();//可伴随传递到前台的Model.Pro一起使用,给下拉框一个默认值。

3.视图页绑定集合以及选中值给下拉框。

 @{                 
    var selectList = new SelectList(ViewBag.ProList as List<SelectListItem>, "Value", "Text", item.Pro);
  }
//使用列表的指定项,数据值字段,数据文本字段,和选定的值来初始化SelectList类的新实例。 @Html.DropDownListFor(modelItem
=> item.Pro, selectList, new { @class = "form-control", id = "dd_pro" })


//modelItem 是foreach(var modelItem in list)的字段。item.Pro是默认选中的值。selectList是下拉列表的实例。

4.传递给后台当前选中值。

var Pro = $(this).parent("td").parent("tr").children().eq(6).find(":selected").text().trim();
//$(this).parent("td").parent("tr").children().eq(6) 是本下拉框在表格中的位置。
//find(":selected")下拉框当前选中项。这里需要的.text()是其显示文本。也可以根据需要传递其真实值。

5.如果只是单纯使用下拉框,也可以用@Html.DropDownList 。

//前台页面:

  @Html.DropDownList("DropDownlist", ViewData["TestList"] as List<SelectListItem>, new { @class = "form-control", id = "ddl_process" })

//后台界面:

public ActionResult TestView()
{
ViewData["TestList"] = GetTestList(); //传递下拉列表数据
return View();
}

//定义一个包含需要的下列列表数据集合
public static List<SelectListItem> GetTestList()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "One", Value = "0" });
items.Add(new SelectListItem { Text = "Two", Value = "1" });
items.Add(new SelectListItem { Text = "Three", Value = "2" });
items.Add(new SelectListItem { Text = "Four", Value = "3" });
return items;
}

以上是最近所做项目中遇到的问题——MVC中用到的一些辅助方法。备以记录,以供查询。

原文地址:https://www.cnblogs.com/jerque/p/8376785.html