C# Tag builder add attribute without value, need to disable the checkbox

627 Views Asked by At

I am trying to generate input checkbox html using Tag Builder in C#, however, searched everywhere and can't seem to add the disabled field to it, as it doesn't allow the value of the attribute to be null or empty.

Is there an alternative way to add an attribute without value???

var builder = new TagBuilder("input");
var checkedProp = true? "checked" : string.Empty;
var disabled = true? "disabled" : string.Empty;
builder.MergeAttribute("type", "checkbox");
builder.MergeAttribute("name", "yolo");
builder.MergeAttribute("checked", checkedProp);
builder.MergeAttribute(disabled, string.Empty); // failed here

Value cannot be null or an empty string. Parameter name: key Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Value cannot be null or an empty string.

Is there a more elegant way to add an attribute without value??? Don't want to use if else statement to add the disabled field

1

There are 1 best solutions below

2
Daniel A. White On

Just conditionally call MergeAttribute and use the string "disabled" to add the attribute.

if (disabled)
{
    builder.MergeAttribute("disabled", "disabled");
}