我正在寻找一种方法来使用单选按钮标签助手上的value属性来通知按钮是否被选中,而不是使用单独的字段进行选择。我找到了@Shyju给related question的答案。我正在使用该答案的修改示例来展示我的意思。是否可以将html中的单选按钮标签助手值属性设置为“checked”?
比方说,我有一个视图模型
public class ExampleViewModel
{
public int Id { get; set; }
public string UserName { get; set; }
public List 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
{
new UserRole {Id = 1, RoleName = "Admin"},
new UserRole {Id = 2, RoleName = "Editor"},
new UserRole {Id = 3, RoleName = "Reader"}
}
};
return View("Example",vm);
}
初始化,并在视图中使用
User name
Select a Role
@for (var i = 0; i < Model.Roles.Count; i++)
{
@Model.Roles[i].RoleName
}
我想实现这一点,是能够读取控制器的post方法中的UserRole.IsSelected字段,以查看特定的UserRole是否是检查与否。如果用户仅检查一个按钮并且不改变选择,则该解决方案起作用。如果用户将选择更改为另一个,则用户触摸的所有UserRole值都将使IsSelected字段为true。
是否可以通过HTML以某种方式设置IsSelected值,以仅显示在表单被提交时检查的按钮,还是需要JavaScript函数?
2016-07-19
Yuhis