【问题标题】:It is possible to use an HTMLHelper not only for an attribute value but instead for the name of the attribute?是否可以将 HTMLHelper 不仅用于属性值,还可以用于属性名称?
【发布时间】:2013-02-27 01:37:52
【问题描述】:

我想根据我传递的特定属性和他的值来生成。这就是我想使用帮助器的方式:

<sometag @PossibleHelper(parameter)/>

PossibleHelper 做完他的事情后,结果可能是这样的:

<sometag attributeName="attributeValue"/>

如何在帮助器中表达这一点?

@helper PossibleHelper(someType){

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

【问题讨论】:

    标签: c# asp.net-mvc html-helper asp.net-webpages razor-2


    【解决方案1】:

    当您使用助手时,它只是常规的剃刀语法。

    @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)
        {
            // ...
        }
    }
    

    【讨论】:

    • 谢谢提里亚尔。我会补充(在阅读和测试一点之后)@functions 也是我所要求的替代方法。
    猜你喜欢
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多