Reputation: 7818
I added a label extension, to add a currency symbol, when the following was called:
@Html.Label("curr", string.Empty, Model.Company.Currency) 39.00
I call it with a parameter, for example: USD
However, when I view the page on screen, it shows:
<label for=''>$</label> 39.00
How do I get it to just show the currency symbol as a label?
Thank you,
Mark
Helpers/LabelExtensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace inv5.Helpers
{
public static class LabelExtensions
{
public static string Label(this HtmlHelper helper, string str, string target, string ccode)
{
String ret = "";
switch (ccode)
{
case "GBP": ret = "£"; break;
case "AUD": ret = "$"; break;
case "BRL": ret = "R$"; break;
case "CAD": ret = "$"; break;
case "CZK": ret = ""; break;
case "DKK": ret = ""; break;
case "EUR": ret = "€"; break;
case "HKD": ret = "$"; break;
case "HUF": ret = ""; break;
case "ILS": ret = "₪"; break;
case "JPY": ret = "¥"; break;
case "MXN": ret = "$"; break;
case "TWD": ret = "NT$"; break;
case "NZD": ret = "$"; break;
case "NOK": ret = ""; break;
case "PHP": ret = "P"; break;
case "PLN": ret = ""; break;
case "SGD": ret = "$"; break;
case "SEK": ret = ""; break;
case "CHF": ret = ""; break;
case "THB": ret = "฿"; break;
case "USD": ret = "$"; break;
default:
ret = "";
break;
}
return String.Format("<label for='{0}'>{1}</label>", target, ret);
}
}
}
Upvotes: 2
Views: 242
Reputation: 2284
Try
public static HtmlString Label(this HtmlHelper helper, string str,string target, string ccode)
and
return MvcHtmlString.Create( String.Format("<label for='{0}'>{1}</label>", target, ret));
Upvotes: 1
Reputation: 56688
The problem with your approach is that MVC encodes output before rendering it into the page. The same happens to your label here, and that is the reason why label is disaplyed as is instead of being processed by the browser.
The best way for MVC to understand your extension correctly is to return MvcHtmlString
instead of plain string:
public static MvcHtmlString Label(this HtmlHelper helper, string str, string target, string ccode)
You should of course build the object of that type:
TagBuilder tag = new TagBuilder("label");
tag.Attributes.Add("for", target);
tag.SetInnerText(ret);
return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
Upvotes: 1