从数据库值创建的DropDownList [英] Creating dropdownlist from values in database

查看:121
本文介绍了从数据库值创建的DropDownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为表角色带有三个字段

I have a table called Roles with three fields


  1. 的Guid角色ID

  2. 字符串ROLENAME

  3. 字符串说明

  1. Guid RoleId
  2. string RoleName
  3. string Description

在我的 register.cshtml 视图我想有一个的DropDownList 其中显示了从<$角色名的列表C $ C>角色表。我还需要能够获得该值,并与它的工作,如分配角色到用户,这将在控制器完成的。
我认为目前看起来类似下面,我使用模型 AspNetUser ,但没有关于角色这是我想在的DropDownList显示什么。

In my register.cshtml view I want to have a dropdownlist which shows the list of RoleName from Roles table. I also need to be able to get that value and work with it, like assigning the Role to user, which will in done in controller. My view currently looks like the one below, i'm using model as AspNetUser but it doesn't have knowledge about Role which is what I want to show in 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>

我的控制器看起来像这样

My controller looks like this

   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();
        }

    }

我需要什么做的,有DropDownList的?

What do I need to do, to have that dropdownlist?

推荐答案

在你的控制器,你需要通过的String [] 的IEnumerable&LT;字符串&GT; )再presenting你的角色进入你的观点在某种程度上...

In your controller you need to pass the string[] (IEnumerable<string>) representing your roles into your view somehow...

有很多方法可以做到这一点,但在你的AccountController您可能执行以下操作:

There are many ways to achieve this, but in your AccountController you could do the following:

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
      });
   }
}

注:我不执行该列表,以任何形式在控制器(我不指定它应该是一个选择列表),我可能要在以不同的方式来显示项目,我让视图是柔性的只透过值,并允许以决定如何呈现的值。

在您的视图那么你可以使用你想要的下拉列表中出现:

In your View you can then use where you want the dropdown list to appear:

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

正如我提到的,有很多方法可以实现你想要什么,但几乎有一件事是肯定的,与ASPNET MVC你将最有可能使用的HTML帮助 DropDownListFor 在这里MSDN文档:

<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor(v=vs.108).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions.dropdownlistfor(v=vs.108).aspx

编辑1:

创建一个模型来保存用户和角色信息,像这样:

Create a model to hold the User and Role informations like so:

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

在控制它可能看起来像这样:

In the controller it could look like so:

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
      });
   }
}

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

In the View you need to update the model to use:

@model Sorama.CustomAuthentiaction.Models.RegisterViewModel

如果您不愿/不能做出这样的改变,你可以添加角色到Viewbag名单:

If you are unwilling/unable to make such a change you could add the list of Roles to the Viewbag:

ViewBag.RoleList = roleProvider.GetAllRoles();

或者,正如你提到的:

Or as you alluded to:

ViewBag.RoleList = Roles.GetAllRoles();

然后在视图像这样访问:

Then access in the View like so:

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

这篇关于从数据库值创建的DropDownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆