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));
}
An attribute has a value that indicates nothingness (null) An attribute exists but has no value (empty)
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.
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.
It's also valid to pass the name of the attribute as the value:
input.Attributes.Add("required", "required");
I've tested on MVC 5, not sure about older versions but the following does what you want.
tagBuilder.MergeAttribute("required", string.Empty);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With