从数据库中的值创建下拉列表

时间:2013-06-14 08:49:36

标签: asp.net-mvc-4 drop-down-menu

我有一个名为Roles的表,其中包含三个字段

  1. Guid RoleId
  2. string RoleName
  3. string Description
  4. 在我的register.cshtml视图中,我希望dropdownlist显示Roles表中的RoleName列表。我还需要能够获得该值并使用它,例如将角色分配给用户,这将在控制器中完成。 我的观点目前看起来如下所示,我使用的模型为AspNetUser,但它不了解Role这就是我要在dropdownlist.中显示的内容

    @model Sorama.CustomAuthentiaction.Models.AspNetUser
    @{
        ViewBag.Title = "Register";
        Layout = "~/Views/shared/_BootstrapLayout.empty.cshtml";
    }
    
    @section Styles{
        <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
    }
    <div class ="form-signin">
    
        @using (Html.BeginForm("Register", "Account"))
        {
            @Html.ValidationSummary(true)
            <h2 class="form-signin-heading"> Register </h2>
            <div class ="input-block-level">@Html.TextBoxFor(model=>model.Email, new{@placeholder = "Email"})</div>
            <div class ="input-block-level">@Html.TextBoxFor(model=>model.UserName, new{@placeholder = "UserName"})</div>
            <div class ="input-block-level">@Html.PasswordFor(model=>model.Password, new{@placeholder ="Password"})</div>
            <div class ="input-block-level">@Html.DropDownListFor(//don't know what to do
    
            <button class="btn btn-large btn-primary" type="submit">Register</button>
        }
    </div>
    

    我的控制器看起来像这样

       public class AccountController : Controller
        {
            //private readonly IDbContext dbContext;
            //
            // GET: /Account/
            [HttpGet]
            public ActionResult Login()
            {
                return View();
            }
    
            [HttpPost]
            [AllowAnonymous]
            public ActionResult Login(LoginModel model)
            {
                if(Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    return RedirectToAction("Index", "Home");
                }
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return View(model);
            }
    
            [HttpGet]
            public ActionResult Register()
            {
                string [] roles = Roles.GetAllRoles();
                return View(roles);
            }
    
            [HttpPost]
            public ActionResult Register(AspNetUser model)
            {
    
                return View();
            }
    
            public ActionResult Index()
            {
                return View();
            }
    
        }
    

    我需要做什么才能拥有该下拉列表?

2 个答案:

答案 0 :(得分:2)

在您的控制器中,您需要以某种方式将代表您角色的string[]IEnumerable<string>)传递给您的视图......

有很多方法可以实现这一目标,但在您的AccountController中, 可以 执行以下操作:

public class AccountController : Controller
{
   private IDbContext dbContext;

   public AccountController(IDbContext dbContext)
   {
       // Made up field that defines your GetAllRoles method
       this.dbContext = dbContext;
   }

   public ActionResult Register()
   {
      // Call the GetAllRoles() and capture the result in a variable called roles
      var roles = dbContext.GetAllRoles();

      return View(new AspNetUser {
         Roles = roles
      });
   }
}

注意:我没有强制执行控制器中的任何形式的列表(我没有指定它应该是一个选择列表),我可能想以不同的方式显示项目,我让通过仅传递值并允许视图决定如何呈现值来使视图变得灵活。

在您的视图中,您可以使用下拉列表显示的位置:

@Html.DropDownListFor(model => model.Roles, Model.Roles
    .Select(role => new SelectListItem { Text = role, Value = role })

正如我所提到的,有很多方法可以实现你想要的东西,但几乎有一点是肯定的,使用aspnet mvc你很可能会在这里使用Html助手DropDownListFor MSDN文档:

http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor(v=vs.108).aspx

编辑1:

创建一个模型来保存用户和角色信息,如下所示:

public class RegisterViewModel
{
   public AspNetUser AspNetUser { get; set; }
   public IEnumerable<string> Roles { get; set; }
}

在控制器中它看起来像这样:

public class AccountController : Controller
{
   private RoleProvider roleProvider;

   public AccountController(RoleProvider roleProvider)
   {
       this.roleProvider = roleProvider;
   }

   public ActionResult Register()
   {
      // Call the GetAllRoles() and capture the result in a variable called roles
      // var roles = roleProvider.GetAllRoles();

      // Or, as you have specified:
      var roles = Roles.GetAllRoles();

      return View(new RegisterViewModel {
         AspNetUser = GetTheAspNetUser(),
         Roles = roles
      });
   }
}

在视图中,您需要更新要使用的模型:

@model Sorama.CustomAuthentiaction.Models.RegisterViewModel

如果您不愿意/无法进行此类更改,可以将角色列表添加到Viewbag:

ViewBag.RoleList = roleProvider.GetAllRoles();

或者你提到:

ViewBag.RoleList = Roles.GetAllRoles();

然后在视图中访问:

@Html.DropDownListFor(model => model.Roles, ViewBag.RoleList
    .Select(role => new SelectListItem { Text = role, Value = role })

答案 1 :(得分:2)

在类似的情况下,我做过类似的事情:

private void BagSelectList()
{
    ViewBag.List = new SelectList(
            db.SetOfCandidateValues, 
            "KeyPropertyOfTheSet", 
            "NameOfThePropertyToAppearInTheDropDownList", 
            selectedValue);
}

在视图中:

@Html.DropDownListFor(
            model => model.ForeignKeyProperty, 
            (SelectList)ViewBag.List)

(当然,如果您不喜欢ViewBag,可以使用强类型视图模型来完成。)

相关问题