Blazor select onchange event value not changed.

huangapple go评论51阅读模式
英文:

Blazor select onchange event value not changed

问题

我有一个<select>在我的Razor视图中。每当更改选择时,我试图将所选选项保存到数据库。

我可以做到使用<input type="text>或任何类型的输入,但我的选择不起作用。

以下是代码:

<select name="expression@(i)"
@onchange="(async e =>
{
    // Test总是等于"1",这是选择的旧值
    var test = e.Value.ToString();
    
    //执行操作
})">
@foreach (var expression in (ExpressionEnum[])Enum.GetValues(typeof(ExpressionEnum)))
{
    <option value="@((int)expression)" selected="@(expression == actionItem.ExpressionEnum)">
        @expression.ToString()
    </option>
}
</select>

如您所述,选择的选项实际上是第一个,"1"。

但即使我尝试选择另一个像"5"这样的选项,test变量仍然等于"1"。

如何获取正确的选择值?

英文:

I have a &lt;select&gt; inside my Razor View. I'm trying to save the selected option in the database whenever the selection is changed.

I'm able to do it with an &lt;input type=&quot;text&quot;&gt; or any type of input, but my select doesn't work.

Here is the code :

&lt;select name=&quot;expression@(i)&quot;
@onchange=&quot;@(async e =&gt;
{
    // Test is always equals to &quot;1&quot;, which is the old value of the select
    var test = e.Value.ToString());
    
    //Do Stuff
})&quot;&gt;

@foreach (var expression in (ExpressionEnum[])Enum.GetValues(typeof(ExpressionEnum)))
{
    &lt;option value=&quot;@((int)actionItem.ExpressionEnum)&quot; selected=@(expression == actionItem.ExpressionEnum)&gt;
        @expression.ToString()
    &lt;/option&gt;
}
&lt;/select&gt;

As commented, the selected option of the select is actually the first one, "1".

But even if I try to select another one like the "5", the test variable will remains equal to "1".

How can I get the correct selected value ?

答案1

得分: 2

actionItem.ExpressionEnum在循环中似乎不会更改,该循环将value设置为,我认为是,&lt;select&gt;中每个选项的1。

我认为你应该将此部分更改为:

value=&quot;@expression&quot;
英文:

actionItem.ExpressionEnum does not seem to change during the loop which sets value to, what I assume to be, 1 for every option in your &lt;select&gt;.

I believe you should change this part:

value=&quot;@((int)actionItem.ExpressionEnum)&quot;

to

value=&quot;@expression&quot;

huangapple
  • 本文由 发表于 2023年4月11日 09:01:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定