2

当调用以下命令时,我添加了一个标签扩展名以添加货币符号:

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

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

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

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

如何让它仅将货币符号显示为标签?

谢谢,

标记

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);
    }
 }
 }
4

2 回答 2

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));
于 2013-06-13T13:19:37.527 回答
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));
于 2013-06-13T13:20:52.230 回答