Radio Button Tag Helpers in ASP.NET 5 MVC 6(ASP.NET 5 MVC 6 中的单选按钮标记帮助程序)
问题描述
我在 ASP.NET 5 MVC 6 中看不到任何单选按钮的标签助手.在我需要使用单选按钮的情况下,处理表单元素的正确方法是什么?
I don't see any tag helpers for radio buttons in ASP.NET 5 MVC 6. What's the right way of handling form elements where I need to use radio buttons?
推荐答案
所有输入类型都有一个 TagHelper,包括单选按钮类型.假设您有这样的视图模型
There is a TagHelper for all the input types which includes the radio button type as well. Assuming you have a view model like this
public class CreateUserVm
{
public string UserName { set; get; }
public IEnumerable<RoleVm> Roles { set; get; }
public int SelectedRole { set; get; }
}
public class RoleVm
{
public int Id { set; get; }
public string RoleName { set; get; }
}
在您的 GET 操作中,
And in your GET action,
public IActionResult Index()
{
var vm = new CreateUserVm
{
Roles = new List<RoleVm>
{
new RoleVm {Id = 1, RoleName = "Admin"},
new RoleVm {Id = 2, RoleName = "Editor"},
new RoleVm {Id = 3, RoleName = "Reader"}
}
};
return View(vm);
}
在视图中,您可以简单地对输入标签使用标记.
In the view, You can simply use markup for the input tag.
@model YourNamespaceHere.CreateUserVm
<form asp-action="Index" asp-controller="Home">
<label class="label">User name</label>
<div class="col-md-10">
<input type="text" asp-for="UserName" />
</div>
<label class="label">Select a Role</label>
<div class="col-md-10">
@foreach (var item in Model.Roles)
{
<input asp-for="SelectedRole" type="radio" value="@item.Id" /> @item.RoleName
}
</div>
<input type="submit" />
</form>
当您发布表单时,所选角色的 Rold Id 将位于 SelectedRole 属性中
When you post your form, The Rold Id for the selected role will be in the SelectedRole property
请记住,上面的 razor 代码将为每个生成的输入生成具有 same Id 属性值和 name 属性值的输入元素由循环.在上面的示例中,它将生成 3 个输入元素(单选按钮类型),其中 Id 和 name 属性值设置为 SelectedRole.当 name 属性值与视图模型中的属性名称(SelectedRole)匹配时,模型绑定将起作用,但重复的 Id 属性值可能会给您的客户端代码带来麻烦(文档中的重复 ID 无效)
Keep in mind that, the above razor code will generate input element with same Id attribute value and name attribute value for each input generated by the loop. In the above example, it will generate 3 input elements(radio button type) with the Id and name attribute value set to SelectedRole. Model binding will work as the name attribute value matches with the property name(SelectedRole) in our view model, but the duplicate Id attribute values might give you trouble with client side code (duplicate Ids in a document is invalid)
这篇关于ASP.NET 5 MVC 6 中的单选按钮标记帮助程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:ASP.NET 5 MVC 6 中的单选按钮标记帮助程序
基础教程推荐
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
