Asp.net MVC3 Razor中的扩展HtmlHelper的返回类型问题

我按照网上的教程自定义helper

public static class HtmlExtensions
{
   
public static string Span(this HtmlHelper helper, string strId,string strContent)
   {
      
return string.Format("<span id=\"{0}\">{1}</span>", strId, strContent);
   }
}
 

然后在页面使用

@using Web.Extentions;
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@Html.Span("span1","这是一个span")  

运行后,显示

Index

<span id="span1">这是一个span</span> 
而不是真正的显示一个span,查看元素,发现生成的是如下的代码
&lt;span id='span1'&gt;这是一个span&lt;/span&gt;


然后我发帖求助, 回复说应该返回MvcHtmlString,代码修改如下

public static MvcHtmlString Span(this HtmlHelper helper, string strId, string strContent)
{
    return MvcHtmlString.Create(string.Format("<span id=\"{0}\">{1}</span>", strId, strContent));

如此就可以正确使用了。

欢迎指教

         

原文地址:https://www.cnblogs.com/gzlisme/p/2339613.html