0

I have an ASP.NET MVC app. My app is displaying values from the model in my view like this:

public static MvcHtmlString ToMeasure<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string measurement = "sf")
{
  if (measurement == "m2")
    measurement = "m<sup>2</sup>";
  return System.Web.Mvc.Html.ValueExtensions.ValueFor(html, expression, "{0:N0} " + measurement);
}

Sometimes, measurement will represent square feet. Other times, it will represent square meters. When its square meters, I want to user the HTML sup tag. Unfortunately, right now, it renders as a literal m<sup>2</sup> instead of as an actual superscript. How do I tell MVC to use a superscript instead of the literal?

Thanks!

1
  • @KrishnaDhungana can you please provide an example? I've never done that before. Commented Apr 15, 2015 at 0:04

1 Answer 1

2

You will need to build the html elements you want to return

public static MvcHtmlString ToMeasure<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string measurement = "sf")
{
    StringBuilder html = new StringBuilder();
    html.Append(ValueExtensions.ValueFor(helper, expression, "{0:N0}"));

    // or html.Append(helper.ValueFor(expression, "{0:N0}"));

    if (measurement == "m2")
    {
        html.Append("m");
        TagBuilder sup = new TagBuilder("sup");
        sup.InnerHtml = "2";
        html.Append(sup.ToString());
    }
    else
    {
        html.Append(measurement);
    }
    // Optionally you might want to wrap it all in another element?
    TagBuilder span = new TagBuilder("span");
    span.InnerHtml = html.ToString();

    return MvcHtmlString.Create(span.ToString());
}

Side note: I suggest you could make this a bit more robust by having a Enum to specify the measurement type, and and passing that to the helper

Edit

In the view use it as

@Html.ToMeasure(m => m.yourProperty, "m2");

and assuming the value of yourProperty is 100, it generates the following output

<span>100m<sup>2</sup></span>
Sign up to request clarification or add additional context in comments.

2 Comments

How do you call it from the view then? Currently, I have @Html.ToMeasure(model => model.Size) and its rendering as System.Web.Mvc.HtmlHelper1[MyApp.MyProject.Models.MyViewModel]`
I have just tested it using @Html.ToMeasure(m => m.myProperty, "m2"); and it works fine. Have you included the relevant assembly in the view? Are you sure you have copied the code exactly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.