简体   繁体   中英

TagBuilder add attribute without value

The same question from here.

How to add attribute without value

This time, I want to create an input with AngularJS attribute, to use it as a directive.

Here is what I want:

<input ng-angular-abc />

This is what the TagBuilder generated:

<input ng-angular-abc=""/>

I have tried this, but none works:

tagBuilder.MergeAttribute("ng-angular-abc", "");
tagBuilder.MergeAttribute("ng-angular-abc", null);
tagBuilder.MergeAttribute("ng-angular-abc", "ng-angular-abc");

This is not exactly what you need, but you can create a helper method to generate the tags -

namespace YourNamespace
{
    public static class CustomHelpers
    {
        public static MvcHtmlString TextboxWithProperty(this HtmlHelper html, string property)
        {
            StringBuilder result = new StringBuilder();
            result.AppendFormat("<input {0} />", property);
            return MvcHtmlString.Create(result.ToString());
        }
    }
}

and call it in your view -

@using YourNamespace
...
...
...
@Html.TextboxWithProperty("ng-angular-abc")

An alternative approach would be to use Razor helpers creating a Helpers.cshtml file in you App_Code directory. Your helper would like this

@helper InputNg() {
    <input ng-angular-abc />
}

To access the helpers in a razor view simply use the filename followed by the method as seen below:

@Helpers.InputNg()

It gives you much better control over your HTML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM