Skip to content

Blazor doesn't render the value attribute if it is set to an empty string #13440

@fire-birdie

Description

@fire-birdie

Blazor doesn't render the value attribute of an option element if the value is an empty string. In other words, this:

<option value="">Test Option</option>

becomes:

<option>Test Option</option>

when rendered to the client. The result is that selecting the option will set the containing select element's value to the text of the option (i.e. Test Option) instead of the empty string.

The same markup, when used inside a .cshtml file, renders the value attribute to the client, allowing for an option that has an empty string as its value. I haven't found a way to do this from a .razor file short of running some Javascript code to set the attribute after the content is rendered.

To Reproduce

  1. Using v3.0.0-preview8 of ASP.NET Core, create a new Blazor application
  2. Add the following to the body tag of _Host.cshtml:
	<script>
		function fixOptionValue(option) {
			option.setAttribute('value', '');
		}
	</script>
  1. Replace the contents of Index.razor with:
@page "/"
@inject IJSRuntime JsRuntime

<select @bind="selectedValue">
	<option selected hidden disabled>Select one</option>
	<option value="">Default behaviour</option>
	<option value="" @ref="EmptyOption" @ref:suppressField>Modified by script</option>
	<option>Option without value</option>
</select>

<div>
	Selected Value: @selectedValue
</div>

@code {
	private string selectedValue;
	private ElementReference EmptyOption;

	protected override async Task OnAfterRenderAsync(
		bool firstRender)
	{
		if (firstRender)
		{
			await this.JsRuntime.InvokeAsync<object>(
				"fixOptionValue",
				this.EmptyOption);
		}
	}
}
  1. Run the app and switch between the options in the select element
  2. Inspect the options in the browser's dev tools

Expected behaviour

Expected the Default behaviour option to have value=""

Metadata

Metadata

Labels

DoneThis issue has been fixedarea-blazorIncludes: Blazor, Razor ComponentsbugThis issue describes a behavior which is not expected - a bug.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions