c# - 是否可以将 HTMLHelper 不仅用于属性值,还可以用于属性名称?

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

我想根据我传递的特定属性及其值来生成。这就是我想要使用助手的方式:

<sometag @PossibleHelper(parameter)/>

PossibleHelper 完成他的工作后,结果可能是这样的:

<sometag attributeName="attributeValue"/>

我如何在助手中表达这一点?

@helper PossibleHelper(someType){

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

最佳答案

当您使用助手时,这只是常规的 razor 语法。

@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 创建一个扩展方法,如果代码在 View 之间共享或有相当多的逻辑,这可能会更好。

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

关于c# - 是否可以将 HTMLHelper 不仅用于属性值,还可以用于属性名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102696/

相关文章:

c# - CS0411 : The type arguments for method 'System.Web.Mvc.Html.EditorExtensions.EditorFor<>)' cannot be inferred from the usage

c# - 如何使自动版本号在 Visual Studio 中工作

c# - `HashSet<T>.IsSubsetOf()` 和 `HashSet<T>.IsProperSubsetOf()` 有什么区别

asp.net - 在 asp.net 核心 Web 应用程序 + Angular 项目中更新 Bootstrap

asp.net-mvc-2 - ASP.NET MVC 2 动态生成模型中的数据注释

asp.net-mvc - 在 HTML 帮助程序中生成 URL

java - 如何对整数除法的结果进行四舍五入?

c# - 使用 WebClient 下载 - IIS 基本身份验证

c# - Web API 脚手架 + MVC View

asp.net-mvc - MVC App 不再通过 Facebook 登录