Reputation: 5827
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!
Upvotes: 0
Views: 1419
Reputation:
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>
Upvotes: 2