DropDownList SelectList SelectedValue问题

时间:2011-04-05 15:33:09

标签: c# asp.net-mvc-3 drop-down-menu

  

可能重复:
  How can I get this ASP.NET MVC SelectList to work?

到底是什么意思? 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);

2 个答案:

答案 0 :(得分:8)

尝试以下方法:

型号:

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")
)

答案 1 :(得分:6)

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