ç单选按钮组使用RadioButtonFor正确的方法为$ C $ [英] Correct Way to Code a Group of Radio Buttons using RadioButtonFor

查看:324
本文介绍了ç单选按钮组使用RadioButtonFor正确的方法为$ C $的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

,正确的方法为code MVC中复选框如下:

Based on my research, the correct way to code a checkbox in MVC is as follows.

@Html.CheckBoxFor(m => m.RememberMe)
@Html.LabelFor(m => m.RememberMe)

这会使一个复选框,渲染复选框的标签,使标签的点击的,这意味着单击标签还切换的复选框。

This will render a checkbox, render a label for the checkbox, and make the label clickable, which means clicking the label also toggles the checkbox.

但是,我们那里有一个单一的视图模型场多个复选框的情况下? (例如,也许每个复选框再presents位的整数值范围内。)或者,更好的,那单选按钮,那里有始终与同一领域相关的几个选项?

But what about the case where there are multiple checkboxes for a single view-model field? (For example, maybe each checkbox represents a bit within an integer value.) Or, better yet, what about radio buttons, where there are always several options associated with the same field?

在这种情况下,似乎有与上述code的问题。或者不是所有的元件将用相同的场,或者与相同的ID将呈现多个元素相关联。

In these cases, there seems to be issues with the code above. Either not all elements would be associated with the same field, or multiple elements with the same ID would be rendered.

我一直在研究这一段时间。我发现有很多的解决方案;然而,它们似乎都既没有一个可点击的标签,或它们需要一束定制和/或非标准的编码。一些避免使用RadioButtonFor / LabelFor完全,而是选择code中的原始的HTML。

I have been researching this for a while now. I have found many solutions; however, they all seem to either not have a clickable label, or they require a bunch of custom and/or non-standard coding. Some avoid the use of RadioButtonFor/LabelFor completely, choosing instead to code the raw HTML.

编码原始HTML是好的,但没有MVC的设计人员没有预料到,我们可能需要多个单选按钮的同场?而且,如果他们做到了,他们怎么意欲它为codeD?

Coding the raw HTML is fine, but didn't the designers of MVC not anticipate that we may need multiple radio buttons for the same field? And, if they did, how did they intended it to be coded?

编辑:

一些研究之后,低于code是我发现到code单选按钮的最佳途径。这code假设我定义一个枚举,我的每个无线电选项。

After researching this some more, the code below is the best way I've found to code radio buttons. This code assumes I've defined an enum for each of my radio options.

@Html.RadioButtonFor(m => m.Gender, Gender.Male, new { id = "gender-male" })
@Html.LabelFor(m => m.Gender, Gender.Male.ToString(), new { @for = "gender-male" })
@Html.RadioButtonFor(m => m.Gender, Gender.Female, new { id = "gender-female" })
@Html.LabelFor(m => m.Gender, Gender.Female.ToString(), new { @for = "gender-female" })

也许这是我能想到最好的,但它仍然困扰我的一点点。

Maybe this is the best I can expect, but it still troubles me a little.


  1. 为什么这么多的定制基本的东西,如标识要求?再次,没有微软预期我们会想与同领域相关的多个单选按钮?

  1. Why is so much customization for basic stuff such as IDs required? Again, didn't Microsoft anticipate that we'd want multiple radio buttons associated with the same field?

如果枚举名是不一样的,因为我想单选按钮标签的描述,这种做法似乎并不支持为字段属性,[显示(NAME = )]

if the enum name isn't the same as the description I want for the radio button label, this approach doesn't seem to support field attributes such as [Display(Name = "")].

(我猜多个复选框正确处理将被推迟到另外一个问题。)

(I guess the correct handling of multiple checkboxes will be deferred to another question.)

推荐答案

好吧,让我们做一些研究。首先,你不需要唯一的ID通过点击标签来切换复选框/收音机。其实你不需要的标识的了!所有你需要做的是包装内部的输入<标签> 标签:

Ok, let's do some research. First of all, you don't need unique id to toggle checkbox/radio by clicking a label. Actually you don't need id at all! All you have to do is wrap your input inside <label> tag:

<label>
    <input type="radio" name="radio" value="1" /> Radio 1   
</label>

到目前为止好,ASP.NET MVC为您提供能力code自己的HTML帮手,让我们写一个枚举示范田!

试想一下,我们有一些注册模型:

Imagine, we've got some registration model:

public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; } 
}

可恶!我只是复制粘贴教程模式O_O。我们现在要什么 - 是让用户的性别,所以我们增加一个性别枚举:

public enum Gender
{
    Iamparanoic = 0,

    Male = 1,

    Female = 2,
}

和增加性别性别字段键入我们的模型(心愿,C#有一个性别访问修饰符!)

and add Gender field of Gender type to our model (wish, c# had a Gender access modifier!)

public Gender Gender { get; set; }

现在,时间使用一些asp.net魔术和写我们的HTML帮助:

Now, time to use some asp.net magic and write our html helper:

public static MvcHtmlString RadioButtonsListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
    var sb = new StringBuilder();
    sb.Append("<ul>"); //we want it to look cool, dont' we?
    foreach (var value in Enum.GetValues(typeof(TEnum)))
    {
        var radio = htmlHelper.RadioButtonFor(expression, value).ToHtmlString(); //you can generage any id and pass it to helper, or use a tagbuilder

        sb.AppendFormat(
            "<li><label>{0} {1}</label></li>",
            radio,
            ((Enum)value).GetEnumName() //instead of it you can grab e.g. Display/Description attribute value or w/e else
        );
    }
    sb.Append("</ul");
    return MvcHtmlString.Create(sb.ToString());
}

和那使用将是这样的:

@Html.RadioButtonsListForEnum(m => m.Gender)

所以pretty,不是吗?当然,你可以添加自定义海拉很多的,像渲染单选按钮具有独特的MVC风格的id,HTML属性等一切kindes但这只是一个样本,屁股踢正确的方式。

So pretty, isn't it? Of course you can add hella lot's of customization, like rendering radiobuttons with unique mvc-style id's, all kindes of html attributes etc. but this is just a sample, ass kick to right way.

接下来,我们也想呈现的CheckBoxList!

Next, we also want to render checkboxlist!

public static MvcHtmlString CheckBoxListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, IDictionary<string, object> htmlAttributes = null)
{
    var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var enumValue = Convert.ToInt32(metadata.Model);

    var sb = new StringBuilder();
    foreach (var value in Enum.GetValues(typeof (TEnum)))
    {
        var val = Convert.ToInt32(value);
        var checkbox = new TagBuilder("input");

        checkbox.MergeAttribute("type", "checkbox");
        checkbox.MergeAttribute("value", value.ToString());
        checkbox.MergeAttribute("name", htmlHelper.NameFor(expression).ToString());

        if ((enumValue & val) == val)
            checkbox.MergeAttribute("checked", "checked");
        if (htmlAttributes != null)
            checkbox.MergeAttributes(htmlAttributes);

        var label = new TagBuilder("label") { InnerHtml = checkbox + ((Enum)value).GetEnumName() };

        sb.Append(label);
        sb.Append("<br/>");
    }
    return new MvcHtmlString(sb.ToString());
}

再次,使用简单:

And again, simple usage:

@Html.CheckBoxListForEnum(m => m.Gender)

顺便说一句,这让刚刚SENCE标有标记属性枚举,当然你必须与模型绑定的麻烦 - 它需要定制粘合剂。但它的另一个问题,我希望乔恩斯基特可以回答这个问题:)

Btw, it makes sence just for enums marked with Flags attribute, and of course you'll have troubles with model binding - it requires custom binder. But it's another question, and i hope Jon Skeet can answer it :)

这篇关于ç单选按钮组使用RadioButtonFor正确的方法为$ C $的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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