JQuery Mobile
JQuery Mobile

Reputation: 6301

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!

Upvotes: 0

Views: 2387

Answers (2)

Mark Cidade
Mark Cidade

Reputation: 99957

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);
}

Upvotes: 1

Stephen Reindl
Stephen Reindl

Reputation: 5819

You may use the DisplayName attribute at the Model. E.g.:

 [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)

Upvotes: 0

Related Questions