简体   繁体   中英

Blazor issue when binding to a select element

I am using @bind-value to bind the selected value of a select element to a variable in Blazor. It works fine, if I physically click the drop down and select a value. However, if I select a value in the drop down through Javascript, Blazor doesn't seem to detect the change. I wrote a very simple program to demonstrate.

Here is my component .cshtml code:

@page "/"
@inject IJSRuntime JsRuntime

<select id="my-select-box" @bind-value="MyValue" @bind-value:event="onchange">
    <option value="0">-- Select Something --</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>

<br />

@if (MyValue == "0") {
    <div>Select an option</div>
} else {
    <div>You chose @MyValue</div>
}

<div style="margin-top: 20px">
    <button @onclick="@(() => SelectOptionThroughJs("1"))">Select Option 1</button>
    <button @onclick="@(() => SelectOptionThroughJs("2"))">Select Option 2</button>
    <button @onclick="@(() => SelectOptionThroughJs("3"))">Select Option 3</button>
</div>

@code {
    public string MyValue {get;set;} = "0";

    public async Task SelectOptionThroughJs(string option)
    {
        await JsRuntime.InvokeVoidAsync("helperFunctions.selectOption", option);
    }
}

And here is my javascript code:

window.helperFunctions = {
    selectOption: function(op) {
        var selectBoxElement = document.getElementById("my-select-box");

        selectBoxElement.value = op;
    }
}

I also created a fiddle to demonstrate .

If you physically select an item from the drop down, you'll see it works just fine. However, if you click one of the 3 buttons, you'll see the value does change in the drop down, but Blazor does not seem to realize the value changed.

How can I fix this issue?

Blazor does not seem to realize the value changed

Exactly... Your select element is bound to the property MyValue, and whenever the current component is rendered, the select element gets its value from the property. Changing the selection through JS Interop has no effect on the property MyValue. The easiest was to solve this issue is to set the value of MyValue to the parameter you pass to the JS function, like this:

MyValue  = option;

but then calling the JS function becomes superfluous... Perhaps, you can tell us what you're trying to achieve.

A point to remember, you shouldn't use JS for such tasks that interfere with the rendering system of Blazor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM