2

Roles3つのフィールドを持つテーブルがあります

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

私のregister.cshtml見解では、テーブルdropdownlistの RoleName のリストを表示する が必要です。Rolesまた、ユーザーにロールを割り当てるなど、その値を取得して操作できるようにする必要があります。これはコントローラーで行われます。私のビューは現在、以下のように見えAspNetUserますRoledropdownlist.

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

    }

そのドロップダウンリストを作成するには、どうすればよいですか?

4

2 に答える 2

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

前述したように、目的を達成する方法はたくさんありますが、ほぼ確実なことが 1 つあります。それは、aspnet mvc では、Html ヘルパーのDropDownListForMSDN ドキュメントを使用する可能性が最も高いということです。

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.RoleList = roleProvider.GetAllRoles();

または、あなたがほのめかしたように:

ViewBag.RoleList = Roles.GetAllRoles();

次に、次のようにビューにアクセスします。

@Html.DropDownListFor(model => model.Roles, ViewBag.RoleList
    .Select(role => new SelectListItem { Text = role, Value = role })
于 2013-06-14T08:54:35.637 に答える
2

同様のシナリオで、私は次のようなことをしました:

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

そしてビューで:

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

(もちろん、 が嫌いならViewBag、強く型付けされたビュー モデルを使用して実行できます。)

于 2013-06-14T08:56:59.337 に答える