我添加了一个标签扩展名,以便在调用以下内容时添加货币符号:
@Html.Label("curr", string.Empty, Model.Company.Currency) 39.00
我用一个参数调用它,例如:USD
但是,当我在屏幕上查看该页面时,它会显示:
<label for=''>$</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 = "£"; 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);
}
}
}
答案 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));