5

我想在下拉列表中选择默认值,其中 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"})
4

3 回答 3

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"})
于 2013-05-21T08:11:48.527 回答
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),因此在决定要预选哪个元素时将使用其值。

于 2013-05-21T08:02:48.250 回答
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)
于 2016-04-20T10:11:37.730 回答