2016-08-22 48 views
0

我需要將一個簡單的過濾器應用於使用剃鬚刀命令@打印到頁面的任何文本。
例如見下面的代碼:Asp.net MVC Razor將過濾器應用到響應文本

public static class MyHelper 
{ 
    public string MyFilter(this string txt) 
    { 
     return txt.Replace("foo", "bar"); 
    } 
} 

在此.cshtml視圖文件

@{ 
    var text = "this is foo!!"; 
} 
<div>@text</div> 

我希望以某種方式來打印this is bar!!代替this is foo!!

+1

您可以爲此創建'HtmlHelper'。 –

+1

你爲什麼要在視圖中而不是在控制器中(應該在哪裏完成)? –

+0

@StephenMuecke,因爲要打印的文本可能位於數據集或變量中或任何可能的位置,我認爲將過濾器應用於剃刀響應比在數據集的每行中運行函數更簡單。 – mhesabi

回答

0

正如@AdilMammadov說,你可以使用HtmlHelper

簡單的C#類static方法:

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>--> 
+0

在你看來,必須指定模型..爲什麼你在View中使用'using'語句?這應該改成'@model MvcApplication1.MyHelpers' ..然後當你調用'FooReplacer'方法時,你只需要做'Model.FooReplacer(「foo foo」)' –

+0

@BviLLe_Kid你是對的,我可以使用'@model MvcApplication1.MyHelpers',但據我所知我的方法也工作正常http://stackoverflow.com/a/3244924/1821692 – feeeper

0

我相信你接近。唯一的問題是你的視圖不知道使用你的過濾器,因爲你沒有在你的視圖中指定它。

這應該工作:

型號

public static class MyHelper 
{ 
    public string MyFilter(this string txt) 
    { 
     return txt.Replace("foo", "bar"); 
    } 
} 

查看

@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" 

我已經爲您創建了dotnetfiddle,表明這將工作。

希望這會有所幫助!

+0

請標記任何一個答案提供爲接受,以便這個問題可以標記爲回答! –