4

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");
Community
  • 1
  • 1
Huy Hoang Pham
  • 4,107
  • 1
  • 16
  • 28
  • 1
    `ng-angular-abc=""` and `ng-angular-abc` are the same. There is no any problems with anuglar when using empty value. I use angular for a while and didn't experienced any difference. –  Dec 30 '14 at 07:15
  • In my directive, I check the attrs and see if the value is defined or not. With ng-angular-abc, the value is undefined, with ng-angular-abc="", the value is empty, and it works wrongly. – Huy Hoang Pham Dec 31 '14 at 01:55
  • It seems like the problem is with your directive... I'd fix that instead of trying to change MVC (which is doing this because all those things are equivalent). If you are really determined, you could inherit from TagBuilder and override `MergeAttribute`. – Casey Mar 23 '15 at 20:22

2 Answers2

1

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")
th1rdey3
  • 4,176
  • 7
  • 30
  • 66
1

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.

benembery
  • 666
  • 7
  • 20