繁体   English   中英

如何从asp.net mvc 4中的SelectList获取项目

[英]how to get item from SelectList in asp.net mvc 4

我正在创建一个自定义注册表格,仅供网站管理员在此注册表格中使用,管理员可以在网站中添加用户并赋予他们角色,因此我使用此模型来定义

public class AddUserToRoleModels
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]
    [Display(Name = "Select Role")]
    public string Roles { get; set; }
}

并在Function类中使此方法添加用户并赋予他们角色

public class Functions
{
    public void AddUserToRole(string UserName,string PassWord,string Role) {

        if (!WebSecurity.UserExists(UserName))
            WebSecurity.CreateUserAndAccount(UserName, PassWord);

        if (!Roles.GetRolesForUser(UserName).Contains(Role))
            Roles.AddUsersToRoles(new[] { UserName }, new[] { Role });
    }
}

然后我创建这个控制器

public class AddUserToRoleController : Controller
{
    UsersContext db = new UsersContext();

    public ActionResult Create()
    {
        ViewBag.RoleId = new SelectList(db.Roles, "RoleId", "RoleName");
        return View();
    }

    [HttpPost]
    public ActionResult Create(AddUserToRoleModels model)
    {
        if (ModelState.IsValid)
        {
            Functions ob = new Functions();

            ob.AddUserToRole(model.UserName, model.Password, model.Roles);

            return RedirectToAction("Index");
        }

        ViewBag.RoleId = new SelectList(db.Roles, "RoleId", "RoleName");
            return View(model);

    }
 }

并为create action控制器创建视图

@model SeniorProject.Models.AddUserToRoleModels

@{
    ViewBag.Title = "Create";
}

 <h2>Create</h2>

 @using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>AddUserToRoleModels</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.UserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.UserName)
        @Html.ValidationMessageFor(model => model.UserName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Password)
        @Html.ValidationMessageFor(model => model.Password)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.ConfirmPassword)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ConfirmPassword)
        @Html.ValidationMessageFor(model => model.ConfirmPassword)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Roles)
    </div>
    <div class="editor-field">
        @Html.DropDownList("RoleId", String.Empty)
        @Html.ValidationMessageFor(model => model.Roles)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

  }

<div>
   @Html.ActionLink("Back to List", "Index")
</div>

 @section Scripts {
   @Scripts.Render("~/bundles/jqueryval")
}

当我尝试添加新用户并赋予他角色时,用户将其插入数据库但没有角色,我认为是因为我试图从@Html.DropDownList("RoleId", String.Empty)获取角色@Html.DropDownList("RoleId", String.Empty)并且是列表,我的方法使用字符串参数作为角色,我尝试从此列表中选择所选项目,但没有可用的乙醚,所以请帮助...

@Html.DropDownListFor(model => model.RoleID, ViewBag.RoleID, "")

或类似的东西。

您还可以将列表作为selectList放在视图模型中,然后将其称为Model.RoleIDs

尝试这个:

public ActionResult Create()
{
    ViewBag.Roles = new SelectList(db.Roles, "RoleId", "RoleName");
    return View();
}

鉴于:

@Html.DropDownListFor(model => model.RoleId, ViewBag.Roles as IEnumerable<SelectListItem>, "Select a role" )

在Post操作if(model.RoleId == 0) ,因此您不选择任何角色。

在控制器中

using (UsersContext db = new UsersContext()){
    var tmp = db.Roles.ToList();
    ViewBag.RoleId = new SelectList(tmp, "RoleId", "RoleName");
}

在视野中

@Html.DropDownListFor(model => model.RoleID, (SelectList)@ViewBag.RoleId)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM