ASP.NET 5 MVC 6中的单选按钮标记助手 [英] Radio Button Tag Helpers in ASP.NET 5 MVC 6

查看:74
本文介绍了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个输入元素(单选按钮类型),并且Idname属性值设置为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中的单选按钮标记助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆