[英]Adding user to roles using check boxes in MVC 4 ASP.NET
我是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>
}
預先感謝您抽出寶貴時間來研究此問題以及您可以提供的任何幫助。
您可以為此使用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.chosen和Html.ListBox幫助器。
對所有枚舉使用EditorTemplates(創建“角色”枚舉):
@model Enum
@Html.DropDownListFor(m => Enum.GetValues(Model.GetType()).Cast<Enum>().Select(m =>
new SelecteListItem {Selected = "your logic", Text = "", Value = ""}))
或按當前枚舉使用自定義局部視圖。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.