我想为其创建扩展方法,如果需要的话HtmlHelper
,允许我创建LabelFor
一个属性显示星号。我怎样才能做到这一点?
public class Foo
{
[Required]
public string Name { get; set; }
}
Html.LabelFor(o => o.Name) // Name*
Answers:
这是一篇博客文章,介绍了如何执行此操作。
为了给您一个从上面的站点修改而来的小示例(注意-我尚未对此进行编译/测试):
namespace HelpRequest.Controllers.Helpers
{
public static class LabelExtensions
{
public static MvcHtmlString Label(this HtmlHelper html, string expression, string id = "", bool generatedId = false)
{
return LabelHelper(html, ModelMetadata.FromStringExpression(expression, html.ViewData), expression, id, generatedId);
}
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")]
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string id = "", bool generatedId = false)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), id, generatedId);
}
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string id, bool generatedId)
{
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
if (String.IsNullOrEmpty(labelText))
{
return MvcHtmlString.Empty;
}
var sb = new StringBuilder();
sb.Append(labelText);
if (metadata.IsRequired)
sb.Append("*");
var tag = new TagBuilder("label");
if (!string.IsNullOrWhiteSpace(id))
{
tag.Attributes.Add("id", id);
}
else if (generatedId)
{
tag.Attributes.Add("id", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName) + "_Label");
}
tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.SetInnerText(sb.ToString());
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
}
}
}
ModelMetadata.FromStringExpression(expression, html.ViewData)
这样我就可以检查meta.IsRequired
并做我想做的事。感谢你的回答。
您可以仅通过CSS将星号添加到必填字段。
首先,为其创建一个CSS类:
.required::after
{
content: "*";
font-weight: bold;
color: red;
}
这会将红色星号附加到具有“必需”类的任何元素上。
然后,在您看来,只需将新类添加到标签中即可:
@Html.LabelFor(m => m.Name, new { @class="required" })
更好的可能是自定义HTML Helper,它可以识别字段是否具有[Required]属性,如果有,则添加required
CSS类。
@Html.LabelFor(m => m.Name, new { @class="required" })
以及您建议的样式。不过,感谢您使我走上正确的道路。
display: inline;
样式以使星号保持同一行。
我这样做是因为我的必填字段必须是动态的(在配置文件中定义)
在视图末尾添加:
<script type="text/javascript">
$('input[type=text]').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
var label = $('label[for="' + $(this).attr('id') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
</script>
$('input[type=text]').each(function () { var req = $(this).attr('data-val-required'); if (undefined != req) { if ($(this).val() === '') $(this).addClass('input-validation-error'); $(this).change(function () { if ($(this).val() === '') $(this).addClass('input-validation-error'); else $(this).removeClass('input-validation-error'); }); }
。
这是我基于Adam Tuliper答案的解决方案,但经过修改可与Bootstrap配合使用,并且还允许使用自定义属性。
using System;
using System.Linq;
using System.Web.Mvc;
using System.Linq.Expressions;
using System.ComponentModel;
public static class RequiredLabel
{
public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (metaData.IsRequired)
labelText += "<span class=\"required\">*</span>";
if (String.IsNullOrEmpty(labelText))
return MvcHtmlString.Empty;
var label = new TagBuilder("label");
label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
{
label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
}
label.InnerHtml = labelText;
return MvcHtmlString.Create(label.ToString());
}
}
然后,我从我的观点这样称呼它:
@Html.RequiredLabelFor(model => model.Category, new { @class = "control-label col-md-3" })
PS确保您不要忘记在视图中包括名称空间。
请在此处查看此帖子-应该包含您所需的大多数内容 http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Creating-tooltips-using-data-annotations-in-ASPNET-MVC.aspx
public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (metaData.IsRequired)
labelText += "<span class=\"required-field\">*</span>";
if (String.IsNullOrEmpty(labelText))
return MvcHtmlString.Empty;
var label = new TagBuilder("label");
label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
label.InnerHtml = labelText;
return MvcHtmlString.Create(label.ToString());
}
使用助手将样式类添加到标签
public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName;
if (!metadata.IsRequired)
{
return html.LabelFor(expression, resolvedLabelText, htmlAttributes);
}
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (attributes == null)
{
return html.LabelFor(expression, resolvedLabelText, htmlAttributes);
}
const string requiredClass = "required-label";
if (attributes.ContainsKey("class"))
{
var classList = attributes["class"].ToString().Split(' ').ToList();
classList.Add(requiredClass);
attributes["class"] = string.Join(" ", classList);
}
else
{
attributes.Add("class", requiredClass);
}
return html.LabelFor(expression, resolvedLabelText, attributes);
}
然后,您可以设置类的样式:
.required-label::after { content : "*" }
基于Renato Saito的上述答案以及评论,并添加$(document).ready并进行检查,以确保我们添加的星号不超过一个(我在某些字段中得到了此标识)原因),我有这个:
// Add asterisks to required fields
$(document).ready(function() {
$("[data-val-required]").each(function () {
var label = $('label[for="' + $(this).attr("id") + '"]');
var asterisksHtml = '<span style="color:red"> *</span>';
if (label.text().length > 0 && label.html().indexOf(asterisksHtml) === -1) {
label.append(asterisksHtml);
}
});
});
尽管这不需要修改LabelFor,但我认为这是最简单的,在ViewModel中只需要1行:
public class FooViewModel
{
[Required(ErrorMessage = "Name is required")]
[Display(Name ="Name*")]
public string Name { get; set; }
}
Html.LabelFor(o => o.Name)
在MVC中使用多种字段类型最适合我
$('input[type=text], input[type=password], input[type=email], input[type=tel], select').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
var label = $('label[for="' + $(this).attr('name') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
使用帮助程序扩展在保留内部化/翻译标签和html属性的必填字段(通过数据注释[必需]定义)之后添加修饰的glyphicon图标
1.创建文件夹“ Helpers”并添加一个新的控制器“ Helper.cs”
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace WIPRO.Helpers
{
public static class Helpers
{
public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string translatedlabelText, object htmlAttributes)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last();
if (metaData.IsRequired)
{
labelText = translatedlabelText + "<span class=\"required\" style=\"color:orange;\"> <span style=\"font-size: 0.4em; vertical-align: super;\" class=\"glyphicon glyphicon-asterisk\" data-unicode=\"270f\"></span></span>";
}
else
{
labelText = translatedlabelText;
}
if (String.IsNullOrEmpty(labelText))
return MvcHtmlString.Empty;
var label = new TagBuilder("label");
label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes))
{
label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true);
}
label.InnerHtml = labelText;
return MvcHtmlString.Create(label.ToString());
}
}
}
2.您认为
@using WIPRO.Helpers
@Html.LabelForRequired(model => model.Test,"Translated text", htmlAttributes: new { @class = "control-label col-md-2" })
代替
@Html.LabelFor(model => model.Test,"Translated text", htmlAttributes: new { @class = "control-label col-md-2" })
希望能帮助到你 ;-)