我需要对使用razor命令@
打印到页面的任何文本应用一个简单的过滤器。
示例代码如下:
public static class MyHelper
{
public string MyFilter(this string txt)
{
return txt.Replace("foo", "bar");
}
}
@{
var text = "this is foo!!";
}
<div>@text</div>
我希望打印this is bar!!
而不是this is foo!!
正如@AdilMammadov所说,你可以使用HtmlHelper
。
带static
方法的简单c#类:
using System;
namespace MvcApplication1.MyHelpers
{
public class MyHelpers
{
public static string FooReplacer(string txt)
{
return txt.Replace("foo", "bar");
}
}
}
并在视图中使用帮助器:
@using MvcApplication1
...
<p>@MyHelpers.FooReplacer("foo foo")</p> <!--returns <p>bar bar</p>-->
我相信你已经很接近了。唯一的问题是你的视图不知道使用你的过滤器,因为你没有在视图中指定它。
这个应该可以工作:
public static class MyHelper
{
public string MyFilter(this string txt)
{
return txt.Replace("foo", "bar");
}
}
<<p> 视图/strong> @model AssemblyName.MyHelper
@{
Layout = null;
var text = Model.MyFilter("Let's go to the foo");
}
<div>@text</div>
// will display "Let's go to the bar"
我已经为您创建了一个。netfiddle,以显示这将工作。
希望这对你有帮助!