Jud*_*dyJ 13 asp.net-mvc asp.net-mvc-3
我希望那里有人有一些想法.我想整理我的代码,所以我已经使用了Html.LabelFor.但是现在我想为标签分配一个CSS类.
Html.LabelFor(model => model.Customer.Description ????)
Run Code Online (Sandbox Code Playgroud)
有没有人知道这是否可能在MVC3中.注意它是我正在使用的MVC3.我已经看到一篇关于MVC2的帖子,并没有简单的解决方案.
Geo*_*e R 15
哥们儿来这里:
namespace System.Web.Mvc.Html
{
using System;
using Collections.Generic;
using Linq;
using Linq.Expressions;
using Mvc;
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
return html.LabelFor(expression, null, htmlAttributes);
}
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)
{
return html.LabelHelper(
ModelMetadata.FromLambdaExpression(expression, html.ViewData),
ExpressionHelper.GetExpressionText(expression),
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes),
labelText);
}
private static MvcHtmlString LabelHelper(this HtmlHelper html, ModelMetadata metadata, string htmlFieldName, IDictionary<string, object> htmlAttributes, string labelText = null)
{
var str = labelText
?? (metadata.DisplayName
?? (metadata.PropertyName
?? htmlFieldName.Split(new[] { '.' }).Last()));
if (string.IsNullOrEmpty(str))
return MvcHtmlString.Empty;
var tagBuilder = new TagBuilder("label");
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
tagBuilder.SetInnerText(str);
return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}
private static MvcHtmlString ToMvcHtmlString(this TagBuilder tagBuilder, TagRenderMode renderMode)
{
return new MvcHtmlString(tagBuilder.ToString(renderMode));
}
}
}
Run Code Online (Sandbox Code Playgroud)
在MVC 3中没有内置的方法来执行此操作.您必须编写执行此操作的帮助程序.看看LabelExtensions课程,看看它是如何完成的.
| 归档时间: |
|
| 查看次数: |
10633 次 |
| 最近记录: |