ASP.NET 5 MVC 6中的单选按钮标记助手

编程入门 行业动态 更新时间:2024-10-10 06:20:32
本文介绍了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操作中,

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

请记住,上面的剃刀代码将为循环生成的每个输入生成具有相同 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中的单选按钮标记助手

本文发布于:2023-11-03 05:15:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554322.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单选   标记   按钮   助手   ASP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!