【发布时间】:2012-03-04 08:21:49
【问题描述】:
我正在寻找有关单选按钮和相关标签的解决方案。我喜欢我们可以通过单击相关标签来选择每个单选按钮的方式。默认情况下,这不是很好。我的意思是标签与单选按钮没有正确关联。
示例:假设我们有一个名为 Revoked 的属性,其可能值为 Yes/No。我们想使用单选按钮让用户选择值。
问题:当从MVC(Html.LabelFor,Html.RadioButtonFor)生成html标签时,两个单选按钮的ID(是/否)是相同的。因此不可能将每个标签与相应的单选按钮相关联。
解决方案:我创建了自己的自定义助手,用于生成具有正确且唯一 ID 的 html 标签。
这是我的助手:
public static MvcHtmlString RadioButtonWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object labelText)
{
object currentValue = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
string property = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
// Build the radio button html tag
TagBuilder htmlRadio = new TagBuilder("input");
htmlRadio.MergeAttribute("type", "radio");
htmlRadio.MergeAttribute("id", property + value);
htmlRadio.MergeAttribute("name", property);
htmlRadio.MergeAttribute("value", (string)value);
if (currentValue != null && value.ToString() == currentValue.ToString()) htmlRadio.MergeAttribute("checked", "checked");
// Build the label html tag
TagBuilder htmlLabel = new TagBuilder("label");
htmlLabel.MergeAttribute("for", property + value);
htmlLabel.SetInnerText((string)labelText);
// Return the concatenation of both tags
return MvcHtmlString.Create(htmlRadio.ToString(TagRenderMode.SelfClosing) + htmlLabel.ToString());
}
它有效,但我需要建议。你怎么看?它有效率吗?我对 ASP.NET MVC 的世界还很陌生,因此非常感谢任何帮助。
谢谢。
【问题讨论】:
标签: asp.net asp.net-mvc