2013-02-27 111 views
2

我想根據我傳遞一個特定的屬性與他的價值產生。這是我要如何使用助手:可以將HTMLHelper不僅用於屬性值,而是用於屬性的名稱?

<sometag @PossibleHelper(parameter)/> 

PossibleHelper後做他的事,這可能是結果:

<sometag attributeName="attributeValue"/> 

我怎樣才能表達,在助手?

@helper PossibleHelper(someType){ 

    if(condition){ 
     attributeName="attributeValue"  //this is wrong 
    } 
} 

回答

2

當你在助手中時,它只是普通的剃刀語法。

@helper PossibleHelper(SomeType something) { 
    if (condition) { 
     <span attributeName="attributeValue">blah</span> 
    } 
} 

您可以設置像這樣的屬性。

@helper PossibleHelper(int something) { 
    var attrValue = string.Empty; 
    if (true) { 
     attrValue = "attributeValue"; 
    } 
    @(string.Format("attribute={0}", attrValue)) 
} 

用法:

<sometag @PossibleHelper(parameter)/> 

僅供參考,也可以使一個擴展方法用於HtmlHelper如果代碼視圖之間共享或有邏輯的一個體面量的可能會更好。

public static class HtmlHelperExtensions 
{ 
    public static MvcHtmlString SomeExtension(this HtmlHelper htmlHelper) 
    { 
     // ... 
    } 
} 
+0

謝謝Tyriar。我會補充(在閱讀和測試一些後)@函數也可以做我想問的東西。 – mjsr 2013-03-21 21:10:26

相關問題