Blazor select onchange event value not changed.

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

Blazor select onchange event value not changed

问题

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

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

以下是代码:

  1. <select name="expression@(i)"
  2. @onchange="(async e =>
  3. {
  4. // Test总是等于"1",这是选择的旧值
  5. var test = e.Value.ToString();
  6. //执行操作
  7. })">
  8. @foreach (var expression in (ExpressionEnum[])Enum.GetValues(typeof(ExpressionEnum)))
  9. {
  10. <option value="@((int)expression)" selected="@(expression == actionItem.ExpressionEnum)">
  11. @expression.ToString()
  12. </option>
  13. }
  14. </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 :

  1. &lt;select name=&quot;expression@(i)&quot;
  2. @onchange=&quot;@(async e =&gt;
  3. {
  4. // Test is always equals to &quot;1&quot;, which is the old value of the select
  5. var test = e.Value.ToString());
  6. //Do Stuff
  7. })&quot;&gt;
  8. @foreach (var expression in (ExpressionEnum[])Enum.GetValues(typeof(ExpressionEnum)))
  9. {
  10. &lt;option value=&quot;@((int)actionItem.ExpressionEnum)&quot; selected=@(expression == actionItem.ExpressionEnum)&gt;
  11. @expression.ToString()
  12. &lt;/option&gt;
  13. }
  14. &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。

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

  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:

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

to

  1. 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:

确定