【问题标题】:How to fill dropdownlist for MVC4 razor views (C#)如何填充 MVC4 剃须刀视图的下拉列表(C#)
【发布时间】:2013-07-10 15:09:36
【问题描述】:

用户配置文件模型

[Table("Users")]
public class UserProfiles
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
    //public string Password { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string MiddleName { get; set; }
    public string Initials { get; set; }

    public string Company { get; set; }
    public string Department { get; set; }
    public string Title { get; set; }
    public string Team { get; set; }
    public string TeamSub { get; set; }
    public string Phone { get; set; }

    public string ImageLocation { get; set; }

    public string Note { get; set; }
    public string Comment { get; set; }

}

控制器

     public ActionResult Index()
    {
        **EDIT :** ViewBag.ProfileId = new SelectList(db.UserProfiles, "UserName", "UserName");
        return View(db.UserProfiles.ToList());
    }

在视图中(我希望/相信这是问题所在)

@model IEnumerable<OilNGasWeb.Models.UserProfiles>

@{
    ViewBag.Title = "CLS - Oil & Gas Web Site Users";
}

<h2>Web Site Users</h2>


    **Removed** @Html.DropDownList(Model => Model.UserName,Model.UserName)
    **Changedinto** @Html.DropDownList("UserName", String.Empty)

新错误:

Exception Details: System.InvalidOperationException: There is no ViewData item of 
type 'IEnumerable<SelectListItem>' that has the key 'UserName'.

【问题讨论】:

标签: asp.net-mvc razor html-select


【解决方案1】:

将 SelectList 添加到 Controller 中的 ViewBag

ViewBag.ProfileId = new SelectList(db.UserProfiles, "Id", "Username");

然后将其添加到您的视图中:

@Html.DropDownList("ProfileId", String.Empty)

此外,您应该在 lambda 表达式中使用“模型”而不是“模型”。

【讨论】:

  • 谢谢,但我被告知不要为此使用 ViewBag,我应该听听这真的重要吗?
  • 在出于某种原因进行更改后,我所有的 @.... 代码都带有下划线,表明我的项目没有任何想法?
  • 似乎用下划线编译和运行,只是奇怪......得到错误 System.InvalidOperationException:没有具有键“用户名”的“IEnumerable”类型的 ViewData 项。使用您的代码
  • 不错,大多数时候应该避免使用 ViewBags,我只在某些情况下将它们用于下拉列表,否则你可以创建一个 ViewModel
  • 在您的情况下将 ViewBag.ProfileId 替换为 ViewBag.UserName。您的 ViewBag 值的名称必须与您的视图中的名称相同。
猜你喜欢
  • 1970-01-01
  • 2013-08-25
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-15
相关资源
最近更新 更多