我是asp.net MVC的初学者。我在要在Get方法中更新的模型中创建了一个List属性。我使用ViewBag将其绑定到视图中的下拉列表。我正在尝试在post方法中获取下拉列表的选定值。
下面是方法。
//UserRole Model
public UserRole()
{
UsersNotInRole = new List<string>();
}
public string Id { get; set; }
public List<string> UsersNotInRole { get; set; }
}
在UsersInRole中更新列表[HttpGet]操作方法:
[HttpGet]
public async Task<IActionResult> UsersInRole(string roleId, string roleName)
{
//Finds the role associated with the specified roleId if any.
var role = await roleManager.FindByIdAsync(roleId);
//initialize the model properties
var model = new UserRole
{
Id = role.Id
};
//add the users not in the role to the UsersNotInRole property in model
foreach (var user in userManager.Users)
{
if (!await userManager.IsInRoleAsync(user, role.Name))
{
model.UsersNotInRole.Add(user.UserName);
}
}
//Binding list to the drop-down list in view using ViewBag
ViewData["UsersNotInRole"] = new SelectList(model.UsersNotInRole);
return View(model);
}
AddUserToRole POST方法:
[HttpPost]
public async Task<IActionResult> AddUserToRole(string roleId, string userName) //userName?? selected from UserNotInRole list
{
var user = await userManager.FindByNameAsync(userName);
if (user == null)
{
TempData["message"] = $"User selected cannot be found";
return RedirectToAction("UsersInRole", new { roleId = role.Id.ToString(), roleName = role.Name.ToString() });
}
// Add user to role
IdentityResult addResult = await userManager.AddToRoleAsync(user, userName);
return RedirectToAction("UsersInRole");
}
//查看
@model UserRole
@{
ViewData["Title"] = $"Users In Role";
}
<h1>@ViewData["Title"]</h1>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group row">
<label class="control-label">Users not in role: </label>
<select asp-for="UsersNotInRole" class="form-control" asp-
items="ViewBag.UsersNotInRole"></select>
<button type="submit" asp-action="AddUserToRole" asp-route-roleId="@Model.Id" class="btn
btn-primary"> Add to Role</button>
</div>
</form>
答案 0 :(得分:2)
您可以使用代替选择标签的方式来使用:
@Html.DropDownListFor(m => m.Id, ViewData["UsersNotInRole"] as SelectList)
答案 1 :(得分:1)
给表单标签一个动作和控制器地址,然后输入一个带有提交类型(或按钮)的输入,然后将模型作为输入传递给后动作。 当用户单击提交输入(或按钮)时,包含用户数据的模型将返回到发布操作,下拉列表的ID以及模型的其他属性也将返回。
<form method="post" action="/controller/action">
<button type="submit" class="btn btn-primary"> Add to Role</button>
</form>
并显示下拉菜单,可以在视图中使用@ Html.DropDown()。如果您不知道该如何使用,请使用下面的链接。
https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor
,您的操作信息应为:
[HttpPost]
public async Task<IActionResult> AddUserToRole(UserRole model)
{
return RedirectToAction("UsersInRole");
}