步骤1(在控制器的ActionResult方法):读取从配置的值:
using System.Configuration;
string configvalue1 = ConfigurationManager.AppSettings["DropdownValues"];
步骤2(在控制器的ActionResult方法):由逗号他们解析到一个数组和修剪的任何空间在前面或解析的文本后面:
string[] values = configvalue1.Split(',').Select(sValue => sValue.Trim()).ToArray();
步骤3(在控制器的ActionResult方法):声明selectlistItem列表,遍历数组填充:
List<SelectListItem> dropDowns = new List<SelectListItem>();
for (int i = 0; i < values.Length; i++)
{
dropDowns.Add(new SelectListItem { Text = values[i], Value = values[i] });
}
步骤4(在控制器的ActionResult方法):在你的ViewBag分配它们:
ViewBag.DropdownVals = dropDowns;
步骤5:(在视图)设置绑定到您的viewbag项的下拉列表。 您需要将其显式转换为IEnumerable SelectListItem对象,否则剃须刀引擎将会生气!
@Html.DropDownList("YourElementName", (IEnumerable<SelectListItem>)ViewBag.DropdownVals, "--Choose Your Value--")
全部控制器:
public ActionResult Index()
{
string[] values = (ConfigurationManager.AppSettings["DropdownValues"]).Split(',').Select(sValue => sValue.Trim()).ToArray();
List<SelectListItem> dropDowns = new List<SelectListItem>();
for (int i = 0; i < values.Length; i++)
{
dropDowns.Add(new SelectListItem { Text = values[i], Value = values[i] });
}
ViewBag.DropdownVals = dropDowns;
return View();
}
完整视图:
@{
ViewBag.Title = "Index";
}
@Html.DropDownList("YourElementName", (IEnumerable<SelectListItem>)ViewBag.DropdownVals, "--Choose Your Value--")
为什么不使用一个数据库,而不是配置文件存储的值? –
因为我将不得不创建一个新的数据库来存储一些值。所有这些应用程序要做的就是获取值并运行查询并显示结果。它非常简单的应用程序。 – Abdul