ASP.Net MVC Helper LabelExtension没有按预期显示

时间:2013-06-13 13:11:05

标签: c# asp.net-mvc asp.net-mvc-3

我添加了一个标签扩展名,以便在调用以下内容时添加货币符号:

 @Html.Label("curr", string.Empty, Model.Company.Currency) 39.00

我用一个参数调用它,例如:USD

但是,当我在屏幕上查看该页面时,它会显示:

<label for=''>&#x24;</label> 39.00

如何才能将货币符号显示为标签?

谢谢,

标记

助手/ 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);
    }
 }
 }

2 个答案:

答案 0 :(得分:1)

您的方法的问题是MVC在将输出呈现到页面之前对输出进行编码。这里的标签也会发生同样的情况,这也就是为什么标签被取消而不是被浏览器处理的原因。

MVC正确理解您的扩展的最佳方法是返回MvcHtmlString而不是普通字符串:

public static MvcHtmlString Label(this HtmlHelper helper, string str, string target, string ccode)

您当然应该构建该类型的对象:

TagBuilder tag = new TagBuilder("label");
tag.Attributes.Add("for", target);
tag.SetInnerText(ret);

return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));

答案 1 :(得分:1)

尝试

public static HtmlString Label(this HtmlHelper helper, string str,string target, string ccode)

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