扩展方法NopLabelFor<TModel, TValue>是另外一种多语言实现方式。
此方法主要是根据特性DisplayNameAttribute的子类NopResourceDisplayName实现对属性名称的描述。此特性是对Model属性的修饰,以指定属性的名称。
例如类AddNewsCommentModel的属性用NopResourceDisplayName特性指定:
namespace Nop.Web.Models.News
{
public partial class AddNewsCommentModel : BaseNopModel
{
[NopResourceDisplayName("News.Comments.CommentTitle")]
[AllowHtml]
public string CommentTitle { get; set; }
[NopResourceDisplayName("News.Comments.CommentText")]
[AllowHtml]
public string CommentText { get; set; }
public bool DisplayCaptcha { get; set; }
}
}
HtmlHelper的扩展方法NopLabelFor的实现如下:
public static MvcHtmlString NopLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, bool displayHint = true)
{
var result = new StringBuilder();
var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
var hintResource = string.Empty;
object value = null;
if (metadata.AdditionalValues.TryGetValue("NopResourceDisplayName", out value))
{
var resourceDisplayName = value as NopResourceDisplayName;
if (resourceDisplayName != null && displayHint)
{
var langId = EngineContext.Current.Resolve<IWorkContext>().WorkingLanguage.Id;
hintResource =
EngineContext.Current.Resolve<ILocalizationService>()
.GetResource(resourceDisplayName.ResourceKey + ".Hint", langId);
result.Append(helper.Hint(hintResource).ToHtmlString());
}
}
result.Append(helper.LabelFor(expression, new { title = hintResource }));
return MvcHtmlString.Create(result.ToString());
}








