TagBuilder add attribute without value

2k Views Asked by At

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");
2

There are 2 best solutions below

2
On

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")
0
On

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.