我的表单有两个下拉菜单:
提交后,授予用户访问该应用程序的权限
之后会进行一些验证,以确保用户还没有访问该应用程序的权限(我不希望在数据库中出现重复项)。我的问题是在验证捕获错误输入并返回错误消息后,先前选择的选项将从下拉列表中消失。查看之前和之后的图像。
这是视图:
@using UserManagement.Models.User;
@model IEnumerable<User>
@{
var users = new List<SelectListItem>();
foreach (var t in Model)
{
users.Add(new SelectListItem() { Text = t.FirstName + " " + t.LastName, Value = t.Id.ToString()});
}
users.Sort((left, right) => left.Text.CompareTo(right.Text));
}
<div class="form-group">
<label class="control-label col-md-2">User</label>
@*
1.Find out if a role was selected in the previous screen
2.Find out if we need to update the table when they select a role
*@
@{
bool hasSelected = false;
if (users.Find(t => t.Text == ViewBag.User) is not null)
{
hasSelected = true;
}
string onchangeString = "";
if (ViewBag.UpdateTable == 1)
{
onchangeString = "onchange = updateTableSelection();";
}
}
<select class="form-control" id="ID" name="ID" @onchangeString>
@* only show this if nothing was selected. Otherwise show the default option *@
@if (!hasSelected)
{
<option value="" disabled selected>--Select a user--</option>
}
@foreach (var u in users)
{
@* add the selected tag to the role that the user had selected in the previous screen *@
if (u.Text == ViewBag.User)
{
<option selected id="u.Text" value="@u.Value">@u.Text</option>
}
else
{
<option value="@u.Value">@u.Text</option>
}
}
</select>
@Html.ValidationMessage("ID", new { @class = "text-danger" })
</div>
我尝试使用 javascript 来更新所选选项,但我似乎无法确定发生这种情况的地点/时间。希望有人了解我不知道的有关所选属性的信息。
我认为你的设计可以重新设计。例如,我会尝试根本不在下拉列表中显示这些值。假设 userA 已经有 AT&T,那么 AT&T 甚至不应该出现在下拉列表中,或者您至少应该禁用它。