0

我打算創建一個MVC的擴展,它看起來像這樣:一次性HtmlString擴展

public static class DivExtension 
{ 

    public static MvcHtmlElement BeginDiv(this HtmlHelper helper) 
    { 

     return new MvcDiv(helper.ViewContext).BeginDiv("",""); 
    } 
    public static MvcHtmlElement BeginDiv(this HtmlHelper helper, string id) 
    { 

     return new MvcDiv(helper.ViewContext).BeginDiv(id,""); 
    } 
} 

在剃刀我可以用這樣的:

@{using(Html.BeginDiv()) 
    { 
     <text> 
       This should appear inside a div <input type="text" value="oi" /> 
     </text> 
    } 
} 

這將產生以下HTML輸出:

<div> 
    This should appear inside a div <input type="text" value="oi" /> 
</div> 

但想象一下,不要僅僅創建一個DIV,我的代碼將獲得一個字符串代表的角色,如果登錄用戶不屬於指定的角色,這個擴展中的HTML應該被抑制:

public static class HtmlAuthSuppressor 
{ 

    public static MvcHtmlElement AuthHTML(this HtmlHelper helper, string roles) 
    { 
     //some code that would allow suppression 
    } 
} 

,如果我使用的是這樣的:

<b>Do you see something below?</b> 
@{using(Html.AuthHTML("Role_Super_User")) 
    { 
     <text> 
       Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" /> 
     </text> 
    } 
} 

最終的HTML輸出,如果用戶不屬於指定的角色,應該是:

<b>Do you see something below?</b> 

這是可能的?

UPDATE: 我知道我可以生成一個像這樣的HTML:

<b>Do you see something below?</b> 
    <!-- 
       Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" /> 
     --!> 

但是,這將揭示的東西,我不希望透露,除了使反應較重不必要的客戶端。

回答

1

你並不需要建立的是,延伸..只是這樣做:

<b>Do you see something below?</b> 

    @if (Request.IsAuthenticated && User.IsInRole("Role_Super_User")) 
    { 
     <text> 
       Congratz!!! You can see this, u are super, indeed. <input type="text" value="oi" /> 
     </text> 
    } 
+0

我知道了!謝謝!但是如果我想(如DIV示例中那樣)將邏輯委託給擴展方法呢?你會推薦做以下事情嗎? '@ {使用(VAR DIV = Html.BeginDiv()){ 如果(div.canBeDisplayed) { 這應該出現一個div內 } } }' – ClayKaboom

+0

這取決於。如果你想要根據不同的角色顯示不同的內容,那麼是的..我不明白爲什麼你不能將它委託給擴展。特別是如果你要做一些比以下更復雜的事情:'用戶。 IsInRole( 「角色名」)'。難道你在實施它時遇到困難,或者你只是想知道別人對此的看法? – Matt

+0

我想要更多的是知道是否可以根據具體情況渲染不同的內容。但我認爲不可能忽略'text'標籤中的內容,並在我的一次性上下文中呈現一些不同的東西(不一定用於認證目的)。 – ClayKaboom