【问题标题】:Populating a razor dropdownlist from a List<object> in MVC从 MVC 中的 List<object> 填充剃刀下拉列表
【发布时间】:2013-08-25 07:03:14
【问题描述】:

我有一个模型:

public class DbUserRole
    {
        public int UserRoleId { get; set; }
        public string UserRole { get; set; }
    }

public class DbUserRoles
    {
        public List<DbUserRole> GetRoles()
        {
            BugnetReports RoleDropDown = new BugnetReports();
            List<DbUserRole> Roles = new List<DbUserRole>();
            DataSet table = RoleDropDown.userRoleDropDown();
            foreach (DataRow item in table.Tables[0].Rows)
            {
                DbUserRole ur = new DbUserRole();
                ur.UserRole = Convert.ToString(item["UserRoleName"]);
                ur.UserRoleId = Convert.ToInt32(item["UserRoleID"]);
                Roles.Add(ur);
            }
            return Roles;
        }
    }

这是加载视图的控制器:

        //
        // GET: /Admin/AddNewUser

        public ActionResult AddNewUser()
        {
            DbUserRoles Roles = new DbUserRoles();
            return View(Roles.GetRoles());
        }

我可以使用@foreach 循环显示列表中的项目,如下所示:

@foreach (var item in Model)
       {
           <tr>
               <td>
                   @item.UserRoleId
               </td>
               <td>
                   @item.UserRole
               </td>
           </tr>
       }

但是如何用传递的模型填充下拉列表,我试过了

@Html.DropDownListFor(x =&gt; x.UserRole)

但我没有运气。

【问题讨论】:

    标签: c# asp.net-mvc-4 razor html.dropdownlistfor


    【解决方案1】:

    接近于:

    @Html.DropDownListFor(m => m.UserRole, 
       new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId), 
       new { /* any html  attributes here */ }) 
    

    您需要一个 SelectList 来填充 DropDownListFor。对于您需要的任何 HTML 属性,您可以添加:

    new { @class = "DropDown", @id = "dropdownUserRole" }
    

    【讨论】:

      【解决方案2】:

      您可以让您的模型包含SelectList&lt;UserRole&gt;,而不是List&lt;UserRole&gt;。还要添加一个属性SelectedUserRoleId 来存储……嗯……选定的UserRole 的Id 值。

      填写SelectList,然后在你的View中使用:

      @Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)
      

      你应该没事的。

      另见http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx

      【讨论】:

        【解决方案3】:

        您对DropDownListFor 的调用需要更多参数来充实它。您需要一个 SelectList,如下面的 SO 问题所示:

        MVC3 DropDownListFor - a simple example?

        有了你所拥有的,你只是告诉它在哪里存储数据,而不是从哪里加载列表。

        【讨论】:

          【解决方案4】:

          一种方法可能是;

              <select name="listbox" id="listbox">
              @foreach (var item in Model)
                     {
          
                             <option value="@item.UserRoleId">
                                @item.UserRole 
                             </option>                  
                     }
              </select>
          

          【讨论】:

          • 好答案,我喜欢完全控制我生成的 html
          • 太棒了!这应该是最好的答案。真正控制 HTML。谢谢:)
          【解决方案5】:

          您可以将您的业务逻辑分离到一个视图模型中,这样您的视图就有了更清晰的分离。

          首先创建一个视图模型来存储用户将选择的 ID 以及将出现在 DropDown 中的项目列表。

          视图模型:

          public class UserRoleViewModel
          {
              // Display Attribute will appear in the Html.LabelFor
              [Display(Name = "User Role")]
              public int SelectedUserRoleId { get; set; }
              public IEnumerable<SelectListItem> UserRoles { get; set; }
          }
          

          参考资料:

          在控制器内部创建一个方法来获取您的UserRole 列表并将其转换为将在视图中呈现的形式。

          控制器:

          private IEnumerable<SelectListItem> GetRoles()
          {
              var dbUserRoles = new DbUserRoles();
              var roles = dbUserRoles
                          .GetRoles()
                          .Select(x =>
                                  new SelectListItem
                                      {
                                          Value = x.UserRoleId.ToString(),
                                          Text = x.UserRole
                                      });
          
              return new SelectList(roles, "Value", "Text");
          }
          
          public ActionResult AddNewUser()
          {
              var model = new UserRoleViewModel
                              {
                                  UserRoles = GetRoles()
                              };
              return View(model);
          }
          

          参考资料:

          现在创建了视图模型,简化了表示逻辑

          查看:

          @model UserRoleViewModel
          
          @Html.LabelFor(m => m.SelectedUserRoleId)
          @Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
          

          参考资料:

          这将产生:

          <label for="SelectedUserRoleId">User Role</label>
          <select id="SelectedUserRoleId" name="SelectedUserRoleId">
              <option value="1">First Role</option>
              <option value="2">Second Role</option>
              <option value="3">Etc...</option>
          </select>
          

          【讨论】:

          • 很高兴您发现它有帮助!
          • 假设这是一个带有过滤器的列表(一个显示由下拉列表中的内容过滤的结果的网格)。您会将网格结果添加到同一视图中吗?谢谢
          • 谢谢,这是我找到的关于这个 razor 扩展的第一个很好的解释,包括阅读官方 MS 文档。
          • 很棒而且很有帮助。这将被收藏以备将来使用! +1
          • 在你的控制器中,当GetRoles方法位于控制器中,而dbUserRoles是模型类的实例时,var roles = dbUserRoles.GetRoles() ...怎么办?
          【解决方案6】:
            @Html.DropDownList("ddl",Model.Select(item => new SelectListItem
          {
              Value = item.RecordID.ToString(),
              Text = item.Name.ToString(),
               Selected = "select" == item.RecordID.ToString()
          }))
          

          【讨论】:

          • “?true : false”不是多余的吗?
          • 我的模型没有选择。你知道为什么吗?
          • using System.Linq; 获取 Select 扩展方法。
          【解决方案7】:
             @{
                  List<CategoryModel> CategoryList = CategoryModel.GetCategoryList(UserID);
                  IEnumerable<SelectListItem> CategorySelectList = CategoryList.Select(x => new SelectListItem() { Text = x.CategoryName.Trim(), Value = x.CategoryID.Trim() });
              }
              <tr>
                  <td>
                      <B>Assigned Category:</B>
                  </td>
                  <td>
                      @Html.DropDownList("CategoryList", CategorySelectList, "Select a Category (Optional)")
                  </td>
              </tr>
          

          【讨论】:

          • 这里有几个答案,但最后一个应该能最好地解决 IMO 的问题。
          【解决方案8】:
          @model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
          @{
              ViewBag.Title = "Detalle";
              Layout = "~/Views/Shared/_Layout.cshtml";
          }
          
          <h2>Ingresar Usuario</h2>
          
          @using (Html.BeginForm())
          {
          
              @Html.AntiForgeryToken()
          <div class="form-horizontal">
          
          
              <hr />
              @Html.ValidationSummary(true, "", new { @class = "text-danger" })
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
                 {
                         new SelectListItem{ Text= "SC", Value = "SC" },
                         new SelectListItem{ Text= "VC", Value = "VC" },
                            new SelectListItem{ Text= "IN", Value = "IN" },
                         new SelectListItem{ Text= "EM", Value = "EM" },
                          new SelectListItem{ Text= "SP", Value = "SP" },
          
                 }, htmlAttributes: new { @class = "form-control" })
                      @Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
                 {
                     new SelectListItem{ Text= "Masculino", Value = "M" },
                     new SelectListItem{ Text= "Femenino", Value = "F" }
                 }, htmlAttributes: new { @class = "form-control" })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
                      @Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
                  </div>
              </div>
          
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
                 {
                     new SelectListItem{ Text= "Soltero", Value = "S" },
                     new SelectListItem{ Text= "Casado", Value = "M" }
                 }, htmlAttributes: new { @class = "form-control" })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
                      @Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
                  </div>
              </div>
          
          
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
                  </div>
              </div>
          
              <div class="form-group">
                  @Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
                  <div class="col-md-10">
                      @Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
                      @Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
                  </div>
              </div>
          
          
          
              <div class="form-group">
                  <div class="col-md-offset-2 col-md-10">
                      <input type="submit" value="Guardar" class="btn btn-default" />
                  </div>
              </div>
              <div class="form-group">
                  <div class="col-md-offset-2 col-md-10" style="color:green">
                      @ViewBag.Message
                  </div>
                  <div class="col-md-offset-2 col-md-10" style="color:red">
                      @ViewBag.ErrorMessage
                  </div>
              </div>
          </div>
          
          
          }
          

          【讨论】:

          • 你能解释一下你的答案吗?这将使您更容易理解您的解决方案。
          • 如果你不解释你的答案和代码,这不是很有帮助。请考虑添加一些说明
          • 他正在手动插入项目。但是,如果您有数百或数千个条目,这不是很有帮助。不过,应该包含 EmployeeViewModelEmployee 以显示那里的对象及其类型。
          【解决方案9】:

          我将处理这个问题,就好像你有一个用户模型:

          Users.cs

          public class Users
          {
              [Key]
              public int UserId { get; set; }
          
              [Required]
              public string UserName { get; set; }
          
              public int RoleId { get; set; }
          
              [ForeignKey("RoleId")]
              public virtual DbUserRoles DbUserRoles { get; set; }
          }
          

          还有一个 DbUserRoles 模型,该模型在数据库中用该名称表示一个表:

          DbUserRoles.cs

          public partial class DbUserRoles
          {
              [Key]
              public int UserRoleId { get; set; }
          
              [Required]
              [StringLength(30)]
              public string UserRole { get; set; }
          }
          

          清理完之后,您应该可以像这样在 Controller 中创建和填充 UserRoles 集合:

          var userRoleList = GetUserRolesList();
          ViewData["userRoles"] = userRolesList;
          

          并具备以下辅助功能:

          private static SelectListItem[] _UserRolesList;
          
          /// <summary>
          /// Returns a static category list that is cached
          /// </summary>
          /// <returns></returns>
          public SelectListItem[] GetUserRolesList()
          {
              if (_UserRolesList == null)
              {
                  var userRoles = repository.GetAllUserRoles().Select(a => new SelectListItem()
                   {
                       Text = a.UserRole,
                       Value = a.UserRoleId.ToString()
                   }).ToList();
                   userRoles.Insert(0, new SelectListItem() { Value = "0", Text = "-- Please select your user role --" });
          
                  _UserRolesList = userRoles.ToArray();
              }
          
              // Have to create new instances via projection
              // to avoid ModelBinding updates to affect this
              // globally
              return _UserRolesList
                  .Select(d => new SelectListItem()
              {
                   Value = d.Value,
                   Text = d.Text
              })
               .ToArray();
          }
          

          Repository.cs

          My Repository function GetAllUserRoles() 的函数,上面:

          public class Repository
          {
              Model1 db = new Model1(); // Entity Framework context
          
              // User Roles
              public IList<DbUserRoles> GetAllUserRoles()
              {
                  return db.DbUserRoles.OrderBy(e => e.UserRoleId).ToList();
              }
          }
          

          AddNewUser.cshtml

          然后在您的视图中执行此操作:

          <table>
              <tr>
                  <td>
                      @Html.EditorFor(model => model.UserName,
                            htmlAttributes: new { @class = "form-control" }
                            )
                  </td>
                  <td>
                      @Html.DropDownListFor(model => model.RoleId,
                            new SelectList( (IEnumerable<SelectListItem>)ViewData["userRoles"], "Value", "Text", model.RoleId),
                            htmlAttributes: new { @class = "form-control" }
                            )
                   </td>
               </tr>
           </table>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-01-25
            • 1970-01-01
            • 2015-10-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多