0

我是 MVC 框架和 ASP.NET 的新手,所以对于任何草率的代码,我深表歉意。

我正在创建一个需要管理员来设置注册新用户角色的应用程序。当管理员登录到应用程序时,他们会自动定向到一个管理员页面,该页面显示已注册该应用程序的用户列表。管理员可以为新用户选择角色。

这是我的管理员控制器:

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

    // GET: /AdminTest/
    [Authorize(Roles = "Admin")]
    public ActionResult Index()
    {

        var model = db.UserProfiles.ToList();
        return View(model);
    }

    [HttpPost]
    public ActionResult Submit(string userName, string selectedRole)
    {
        Roles.AddUserToRole(userName,selectedRole);
        return View("Index");
    }

这是相应的视图:

@model IEnumerable<WAP.Models.UserProfile>

@{
   ViewBag.Title = "Index";
}

...

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.UserId)
    </td>
    <td>

    </td>
    <td>
        @Html.DisplayFor(modelItem => item.UserName)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.UserId }) |
        @Html.ActionLink("Details", "Details", new { id=item.UserId }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.UserId })

        @using (Html.BeginForm("Submit", "AdminTest", FormMethod.Post))
        {

            <select name ="selectedRole">
              <option value="Null"></option>
              <option value="Manager">Manager</option>
              <option value="Agent">Agent</option>
            </select>

            <input id="SubmitChange" type="submit" value="Submit" /> 
            <input id="userName" type ="text" value= "@item.UserName" name= "userName" hidden ="hidden" />
        }
    </td>
</tr>

}


提前感谢您抽出宝贵时间查看此问题以及您可以提供的任何帮助。

4

2 回答 2

1

您可以为此使用Html.DropDownList助手。首先,您需要在控制器中准备角色集合以填充它。这是示例代码:

[Authorize(Roles = "Admin")]
public ActionResult Index()
{
    var model = db.UserProfiles.ToList();
    var rolesCollection = new List<string> {"Null", "Manager", "Agent"};
    ViewBag.Roles = new SelectList(rolesCollection);
    return View(model);
}

那么在你看来:

@using (Html.BeginForm("Submit", "AdminTest", FormMethod.Post))
{
    @Html.Hidden("userName", item.UserName)
    @Html.DropDownList("selectedRole", (SelectList)ViewBag.Roles)

    <input id="SubmitChange" type="submit" value="Submit" /> 
}

您还可以通过以下方式使用Html.RadioButton助手:

@using (Html.BeginForm("Submit", "AdminTest", FormMethod.Post))
{
    @Html.Hidden("userName", item.UserName)

    @Html.RadioButton("selectedRole", "Null", true)
    @Html.RadioButton("selectedRole", "Manager")
    @Html.RadioButton("selectedRole", "Agent")

    <input id="SubmitChange" type="submit" value="Submit" /> 
}

如果要同时选择多个角色,我建议使用一些 jQuery 插件,例如jQuery.chosenHtml.ListBox helper。

于 2013-10-07T08:08:58.183 回答
0

对所有枚举使用 EditorTemplates(创建“角色”枚举):

@model Enum 
@Html.DropDownListFor(m => Enum.GetValues(Model.GetType()).Cast<Enum>().Select(m => 
new SelecteListItem {Selected = "your logic", Text = "", Value = ""}))

或按当前枚举使用自定义局部视图。

于 2013-10-07T11:14:31.857 回答