I have setup the following loop, which correctly populates a select control:
<select name="apisel" id="apisel" onchange="SelectedIndexChanged">
@foreach (var item in Model.APIs)
{
<option value="@item.ApiID" @item.SelectedString>
@item.ApiTitle
</option>
}
</select>
I am trying to use @item.SelectedString
to add the string "selected" into the page for the selected combo box item.
However, this is not working. So as a test, I just forced that string to always be "test", however, the page generates the HTML without the @item.SelectedString
ever showing up! In addition, the space before @item.SelectedString
is also not there.
Does anyone know why this is? Is Razor trying to do something "smart" here?
The new Tag Helpers are overriding your attempts.
You can manually opt-out for the <option>
elements with !
<select name="apisel" id="apisel" onchange="SelectedIndexChanged">
@foreach (var item in Model.APIs)
{
<!option value="@item.ApiID" @item.SelectedString>
@item.ApiTitle
</!option>
}
</select><br/><br/>
You generally cannot output arbitrary strings within HTML tags. The HTML is actually parsed by Razor for its tag helpers feature, so it needs to be well-formed. If you try to do that, you will just get the following error:
error RZ1031: The tag helper 'option' must not have C# in the element's attribute declaration area.
You can disable the tag helper parsing there by adding a !
in front of the tag name:
<!option value="@item.ApiID" @item.SelectedString>@item.ApiTitle</!option>
A much better option however would be to simply use the tag helper to select the option: You don’t actually need to construct a SelectedString
that just contains "selected"
. Instead, you can just set the selected
attribute of the element (or rather the tag helper) to a boolean:
<option value="@item.ApiID" selected="@item.IsSelected">@item.ApiTitle</option>
This will properly set the selected
attribute when item.IsSelected
is true, or omit the attribute completely when it is false.
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