c# - Blazor 将多个选择绑定(bind)到一个值

标签 c# html asp.net-core razor blazor

我正在尝试将一个多选绑定(bind)到一个值,然后将该值传递给一个模型,但目前它只返回一个值,我尝试将它从一个字符串更改为一个字符串数组,但出现了很多错误并且不能找到解决方案。

有谁知道如何返回用户选择的所有值?

谢谢!

<div class="form-group col-md-6">
   <label for="dur">Duration</label>
   <select @bind="Duration" class="custom-select" id="dur" multiple>
      <option value="12" selected>One Year</option>
      <option value="24">Two Year</option>
      <option value="36">Three Year</option>
      <option value="48">Four year</option>
      <option value="60">Five Year</option>
   </select>
   <small class="form-text text-muted">Hold <b>'CTRL'</b> to select multiple.</small>
</div>

@code {

 private string _Duration;

       private string Duration
        {
            get => _Duration;
            set
            {
                if (value != _Duration)
                {
                    _Duration = value;
                    UpdateModel();
                }
            }
        }
}

最佳答案

<select multiple >
@foreach (var item in myVar)
{
   <option value="@item.SlctValue" @onclick=@((e) => OptionClickEvent(@item.SlctValue,e))>@item.SlctName</option>
}
</select>

@foreach (var holderItem in myHolder)
{
   @holderItem
}



@code  {
   private List<string> myHolder = new List<string>();

   private List<SelectModel> myVar = new List<SelectModel>()
   {
      new SelectModel(){ SlctValue = 1, SlctName="One Year" },
      new SelectModel(){ SlctValue = 2, SlctName="Two Year" },
      new SelectModel(){ SlctValue = 3, SlctName="Three Year"},
      new SelectModel(){ SlctValue = 4, SlctName="Four Year" },
   };

   public void OptionClickEvent(int values,MouseEventArgs evnt)
   {
       if (evnt.CtrlKey)
       {
           myHolder.Add(values.ToString());
       }
   }

   public class SelectModel
   {
       public string SlctName { get; set; }
       public int SlctValue { get; set; }
   }

}

关于c# - Blazor 将多个选择绑定(bind)到一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67869897/

相关文章:

c# - 匿名方法 - 3 种不同的方式 - 异步

c# - .net 核心中的 IHttpClientFactory

c# - Authorize Action 过滤器和 Authorization 过滤器有什么区别?

c# - 如何将两个字符串(日期和时间)合并为一个 DateTime

c# - 使用 NUnit 在不同的应用程序域中运行单元测试

c# - 使用 Mono P/Invoke : Why? 的 DllNotFoundException

javascript/jquery 根据输入到文本输入字段中的值更改 html 元素

html - 如何在表格上方添加空间?填充不起作用

html - 如何将 CSS 应用于 :last-child button

c# - 在共享 Linux 主机上托管 ASP.NET Core 应用程序