Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attribute without value

I am generating HTML textbox through the html helper and TagBuilder.

we have the method TagBuilder.Attributes.Add("key","value")

but for HTML5 required attribute does not need value to be passed, so if i pass empty string then the output with value of required = ""

So how do i add required attribute without passing the value?

 public static IHtmlString AppTextBox(this HtmlHelper helper, string model)
    {
        var input = new TagBuilder("input");
        input.Attributes.Add("class", "form-control");
        input.Attributes.Add("ng-model", model);

        input.Attributes.Add("required","");

        return new MvcHtmlString(input.ToString(TagRenderMode.Normal));
    }
like image 675
Srini Avatar asked Oct 29 '13 21:10

Srini


People also ask

Can attributes have no value?

An attribute has a value that indicates nothingness (null) An attribute exists but has no value (empty)

How do you make an empty attribute?

To set an attribute without a value, select the element and call the setAttribute() method on it, e.g. button. setAttribute('disabled', '') . If we pass an empty string as a second parameter to the setAttribute method, the attribute is set without a value.

How do you add attributes?

To create a new attribute:Right click on any of the existing attributes and select Insert Row or scroll down to the bottom of the attributes and place the cursor in the first empty field under Description. In the Data Type column, select the appropriate data type.


2 Answers

It's also valid to pass the name of the attribute as the value:

input.Attributes.Add("required", "required");
like image 93
Henk Mollema Avatar answered Oct 10 '22 02:10

Henk Mollema


I've tested on MVC 5, not sure about older versions but the following does what you want.

tagBuilder.MergeAttribute("required", string.Empty);
like image 32
benembery Avatar answered Oct 10 '22 04:10

benembery