简体   繁体   中英

Update Label Text in ASP.NET MVC Html Helper

I have an ASP.NET MVC app. I am rendering the view with the help of Html Helpers. For example, my .cshtml file looks like the following:

<div>
  @Html.Label(model => model.Price)
  @Html.TextPrice(model => model.Price)
</div>

The helpers are defined like the following in Extensions.cs:

public static MvcHtmlString Label<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string classes = "control-label")
{
  var attr = new Dictionary<string, object>();
  attr .Add("class", classes);

  return System.Web.Mvc.Html.LabelExtensions.LabelFor(html, expression, attr);
}

public static MvcHtmlString TextPrice<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, byte decimalPlaces = 2, string classes = "form-control")
{
  return Text(html, expression, classes + " decimal-" + decimalPlaces.ToString());
}

Eventually, I want to translate the labels into other languages. For now, I need to do an intermediary translation. My question is, when I print a label, how do I grab the text, alter it, then use the new text for the label? I do NOT want to add a bunch of Display attributes on my model at this time. I just need to do a quick-and-dirty search and replace in my Label extension method. However, I'm just not sure how to grab the text and update it.

Thank you!

You can get the property name from the expression yourself and then pass the translation, as an argument for the labelText parameter, to LabelExtensions.LabelFor() :

public static MvcHtmlString Label<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string classes = "control-label")
{
    var attr = new Dictionary<string, object>();
    attr .Add("class", classes);

    string propertyName = ((MemberExpression)expression.Body).Member.Name;
    string labelText = translate(propertyName);

    return System.Web.Mvc.Html.LabelExtensions.LabelFor(html, expression, labelText, attr);
}

You may use the DisplayName attribute at the Model. Eg:

 [Display(Name="Character_FirstName", ResourceType=typeof(ClassLib1.Resources))]
 public string FirstName {get; set;}

See for example: http://haacked.com/archive/2011/07/14/model-metadata-and-validation-localization-using-conventions.aspx/ or https://stackoverflow.com/a/3877154/2298807 (related to Localization of DisplayNameAttribute )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM