Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor is not writing my "selected" value into the page

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?

like image 413
A X Avatar asked Aug 04 '18 19:08

A X


2 Answers

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/>
like image 117
Jasen Avatar answered Sep 21 '22 10:09

Jasen


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.

like image 21
poke Avatar answered Sep 21 '22 10:09

poke