DropDownList SelectList SelectedValue问题

iLe*_*ing 2 c# asp.net-mvc-3 drop-down-menu

可能重复:
如何让这个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);
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

请尝试以下方法:

模型:

public class MyViewModel
{
    public int CategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

控制器:

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
        })
    };
}
Run Code Online (Sandbox Code Playgroud)

视图:

@Html.DropDownListFor(
    x => x.CategoryId,
    new SelectList(Model.Categories, "Value", "Text")
)
Run Code Online (Sandbox Code Playgroud)


Tim*_*mbo 6

我认为您需要将所选值设为字符串.使用扩展方法也有一些价值,详见此处.