我一直在寻找一种方法来使用单选按钮标记帮助器上的value属性来通知是否选中了按钮,而不是使用单独的字段进行选择。我找到@Shyju给related question的答案。我正在使用该答案的修改示例来说明我的意思。
我们说我有一个viewmodel
public class ExampleViewModel
{
public int Id { get; set; }
public string UserName { get; set; }
public List<UserRole> Roles { get; set; }
}
public class UserRole
{
public int Id { get; set; }
public string RoleName { get; set; }
public bool IsSelected { get; set; }
}
在控制器中初始化
public IActionResult Example()
{
var vm = new ExampleViewModel
{
Roles = new List<UserRole>
{
new UserRole {Id = 1, RoleName = "Admin"},
new UserRole {Id = 2, RoleName = "Editor"},
new UserRole {Id = 3, RoleName = "Reader"}
}
};
return View("Example",vm);
}
并在视图中使用
<form asp-controller="Example" asp-action="Save">
<label class="label">User name</label>
<div class="col-md-10">
<input asp-for="UserName" type="text" />
</div>
<label class="label">Select a Role</label>
<div class="col-md-10">
<div class="btn-group" data-toggle="buttons">
@for (var i = 0; i < Model.Roles.Count; i++)
{
<label class="btn btn-default">
<input asp-for="Roles[i].Id" type="radio" value="@Model.Roles[i].Id" />
<input asp-for="Roles[i].IsSelected" type="radio" value=true />
@Model.Roles[i].RoleName
</label>
}
</div>
</div>
<input type="submit" />
</form>
我想要实现的目的是能够在控制器的post方法中读取UserRole.IsSelected字段,以查看是否检查了特定的UserRole。如果用户只检查一个按钮并且不改变选择,则此解决方案有效。如果用户将选择更改为另一个,则用户触摸的所有UserRole值都将IsSelected字段设为true。
是否有可能以某种方式使用HTML设置IsSelected值,以仅显示提交表单时检查的按钮,还是需要JavaScript函数?
答案 0 :(得分:4)
您的模型对于单选按钮(用于从多个选择中选择一个)没有意义。如果您只想选择一个角色,那么您的模型需要
public class ExampleViewModel
{
public int Id { get; set; }
public string UserName { get; set; }
public int SelectedRole { get; set; }
public List<UserRole> RolesList { get; set; }
}
public class UserRole
{
public int Id { get; set; }
public string RoleName { get; set; }
}
并在视图中
@foreach(var role < Model.RolesList)
{
<label class="btn btn-default">
<input asp-for=SelectedRole" type="radio" value="role.Id" />
<span>@role.RoleName<span>
</label>
}
在POST方法中,SelectedRole
的值将包含所选Id
的{{1}}
如果您想要选择多个角色,则使用您现有的模型,但视图将变为
UserRole
在POST方法中,您可以使用
获取所选角色@for (var i = 0; i < Model.Roles.Count; i++)
{
<label class="btn btn-default">
<input asp-for="Roles[i].Id" type="hidden"/>
<input asp-for="Roles[i].IsSelected" type="checkbox"/>
<span>@Model.Roles[i].RoleName</span>
</label>
}