Mark
Mark

Reputation: 7818

ASP.Net MVC Helper LabelExtension not showing as expected

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=''>&#x24;</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 = "&#xa3;"; break;
            case "AUD": ret = "&#x24;"; break;
            case "BRL": ret = "R&#x24;"; break;
            case "CAD": ret = "&#x24;"; break;
            case "CZK": ret = ""; break;
            case "DKK": ret = ""; break;
            case "EUR": ret = "€"; break;
            case "HKD": ret = "&#x24;"; break;
            case "HUF": ret = ""; break;
            case "ILS": ret = "₪"; break;
            case "JPY": ret = "&#xa5;"; break;
            case "MXN": ret = "&#x24;"; break;
            case "TWD": ret = "NT&#x24;"; break;
            case "NZD": ret = "&#x24;"; break;
            case "NOK": ret = ""; break;
            case "PHP": ret = "P"; break;
            case "PLN": ret = ""; break;
            case "SGD": ret = "&#x24;"; break;
            case "SEK": ret = ""; break;
            case "CHF": ret = ""; break;
            case "THB": ret = "฿"; break;
            case "USD": ret = "&#x24;"; break;

            default:
                ret = "";
                break;
        }
        return String.Format("<label for='{0}'>{1}</label>", target, ret);
    }
 }
 }

Upvotes: 2

Views: 242

Answers (2)

maxs87
maxs87

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

Andrei
Andrei

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

Related Questions