我想在下拉列表中选择默认值,其中policyId = 7但它没有选择该值,我做错了什么?
控制器:
var pm = new ManagerClass();
IEnumerable<myClass> po = pm.GetDataFromDb();
IEnumerable<SelectListItem> Policies = new SelectList(po, "PolicyID", "PolicyName", new { PolicyID = 7 });
ViewBag.Policies = Policies;
查看:
@Html.DropDownListFor(m => m.PolicyID, ViewBag.Policies as IEnumerable<SelectListItem>, new { @class = "dropdown-field"})
答案 0 :(得分:8)
这是因为它实际上没有选择SelectList
中的值。
首先,为了使它更好,将项目放在视图模型中以防止演员(这也是更好的练习):
public class MyModel
{
public int PolicyID { get; set; }
public List<SelectListItem> Policies { get; set; }
//rest of your model
}
然后填充它:
var model = new MyModel();
model.Policies = po
.Select(p => new SelectListItem
{
Text = p.PolicyName,
Value = p.PolicyID.ToString(),
Selected = p.PolicyID == currentPolicyId //change that to whatever current is
})
.ToList();
然后在你看来,做:
@Html.DropDownListFor(m => m.PolicyID, Model.Policies, new { @class = "dropdown-field"})
答案 1 :(得分:7)
只需将视图模型上的PolicyID
属性设置为您要预选的值:
var pm = new ManagerClass();
var po = pm.GetDataFromDb();
ViewBag.Policies = new SelectList(po, "PolicyID", "PolicyName");
viewModel.PolicyID = 7;
return View(viewModel);
由于您的DropDownList绑定到PolicyID
属性(m => m.PolicyID
),因此在决定要预选哪个元素时将使用其值。
答案 2 :(得分:0)
这是DropDownList:
控制器:
列出FieldListItems = new List();
FieldListItems.Add(new SelectListItem {Text =“Project ID”,Value =“Project_ID”});
FieldListItems.Add(new SelectListItem {Text =“Project Name”,Value =“Project_Name”});
ViewBag.SearchByList = new SelectList(FieldListItems,“Value”,“Text”,selectedValue:Project_ID);
观点:
排序方式:@ Html.DropDownList(“sortOrder”,(SelectList)ViewBag.SortingByList)
您可以将控制器中的selectedValue更改为您想要的项目为默认值
答案 3 :(得分:0)
如果您有静态菜单:
1-创建以下类:
public static class StaticMenus
{
public static List<string> GetGridRowsCount()
{
List<string> result = new List<string>();
result.Add("3");
result.Add("5");
result.Add("10");
result.Add("20");
result.Add("25");
result.Add("50");
result.Add("100");
return result;
}
}
2-将以下代码添加到您的控制器:
ViewData["CountryList"] = new SelectList(StaticMenus.GetGridRowsCount(),"10");
3-将以下代码添加到您的视图中:
@Html.DropDownList("MainGridRowsCount", ViewData["RowsCountList"] as SelectList)