【问题标题】:DropDownList SelectList SelectedValue issue [duplicate]DropDownList SelectList SelectedValue问题[重复]
【发布时间】:2011-04-05 23:38:58
【问题描述】:

可能重复:
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);

【问题讨论】:

  • 你能确认 cat 变量中确实有类别吗?

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


【解决方案1】:

尝试以下方法:

型号:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-19
      • 2013-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多