DropDownList SelectList SelectedValue issue

本文关键字:issue SelectedValue SelectList DropDownList | 更新日期: 2023-09-27 17:49:19

可能重复:
如何使此ASP.NET MVC SelectList正常工作?

这到底是什么?MVC3的DropDownList中是否存在某种错误?SelectedValue在标记中不会显示为实际选中。

我正在尝试不同的方法,但没有任何效果。

public class SessionCategory
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public static IEnumerable<SessionCategory> Categories
{
     get
      {
          var _dal = new DataLayer();
          return _dal.GetSesionCategories();
      }
}
@{
        var cats = Infrastructure.ViewModels.Session.Categories;
        var sl = new SelectList(cats, "Id", "Name",2);
}
@Html.DropDownList("categories", sl);

DropDownList SelectList SelectedValue issue

尝试以下操作:

型号:

public class MyViewModel
{
    public int CategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}

控制器:

public ActionResult Foo()
{
    var cats = _dal.GetSesionCategories();
    var model = new MyViewModel
    {
        // Preselect the category with id 2
        CategoryId = 2,
        // Ensure that cats has an item with id = 2
        Categories = cats.Select(c => new SelectListItem
        {
            Value = c.Id.ToString(),
            Text = c.Name
        })
    };
}

视图:

@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.Categories, "Value", "Text")
)

我认为您需要将所选值设为字符串。使用这里详细介绍的扩展方法也有一些价值。