【问题标题】:Blazor jquery select2 two way bindingBlazor jquery select2 双向绑定
【发布时间】:2020-03-26 04:01:54
【问题描述】:

我在 blazor 服务器端使用 jquery select2 如何绑定选定的值

<InputSelect class="form-control select2" @bind-Value="@purchaseSearch.PriorityId" id="search-priorityId">
<option value="">All</option>
@foreach (var priority in priorities)
{
<option value="@priority.Id">@priority.Name</option>
}
</InputSelect>

【问题讨论】:

    标签: c# asp.net-mvc blazor-server-side


    【解决方案1】:

    我已经为 blazor 创建了一个带有 select2 库的自定义组件选择。 我希望这是你的榜样。 - Select2.razor:

    @typeparam TValue
    @inherits InputBase<TValue>
    @if (!string.IsNullOrWhiteSpace(Label))
    {
        <label class="form-control-label" for="@Id">
            @Label
            @if (Required)
            {
                <font color="red">(*)</font>
            }
        </label>
    }
    else
    {
        <LabelFor FieldIdentifier="FieldIdentifier"></LabelFor>
    }
    <select id="@Id" class="form-control select2" style="width: 100%;" >
        <option @key="null" value="null">--- Chọn ---</option>
        @if (Datasource != null)
            @foreach (var item in Datasource)
            {
                if (item.Key == Value?.ToString())
                {
                    <option @key="@item.Key" value="@item.Key" selected="selected">
                        @((MarkupString)@item.Value)
                    </option>
                }
                else
                {
                    <option @key="@item.Key" value="@item.Key">
                        @((MarkupString)@item.Value)
                    </option>
                }
            }
    </select>
    <div class="form-control-validation">
        <CustomValidationMessage  Field="FieldIdentifier" TValue="string" />
    </div>
    
    • Select2.razor.cs

      public partial class SelectWithFilter<TValue> : InputBase<TValue>
      {
              [Parameter] public string Id { get; set; }
              [Parameter] public string Label { get; set; }
              [Parameter] public bool Required { get; set; }
              //[Parameter] public Expression<Func<string>> ValidationFor { get; set; }
              [Parameter] public ICollection<KeyValuePair<string, string>> Datasource { get; set; }
              [Inject] IJSRuntime JSRuntime { get; set; }
              public DotNetObjectReference<SelectWithFilter<TValue>> DotNetRef;
              protected override bool TryParseValueFromString(string value, out TValue result, out string validationErrorMessage)
              {
                  if (value == "null")
                  {
                      value = null;
                  }
                  if (typeof(TValue) == typeof(string))
                  {
                      result = (TValue)(object)value;
                      validationErrorMessage = null;
      
                      return true;
                  }
                  else if (typeof(TValue) == typeof(int) || typeof(TValue) == typeof(int?))
                  {
                      int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedValue);
                      result = (TValue)(object)parsedValue;
                      validationErrorMessage = null;
      
                      return true;
                  }
      
                  throw new InvalidOperationException($"{GetType()} does not support the type '{typeof(TValue)}'.");
              }
      
              protected override void OnInitialized()
              {
                  base.OnInitialized();
                  DotNetRef = DotNetObjectReference.Create(this);
              }
      
              protected override async Task OnAfterRenderAsync(bool firstRender)
              {
                  await base.OnAfterRenderAsync(firstRender);
                  if (firstRender)
                  {
                      await JSRuntime.InvokeVoidAsync("select2Component.init", Id);
                      await JSRuntime.InvokeVoidAsync("select2Component.onChange", Id, DotNetRef, "Change_SelectWithFilterBase");
                  }
              }
      
              [JSInvokable("Change_SelectWithFilterBase")]
              public void Change(string value)
              {
                  if (value == "null")
                  {
                      value = null;
                  }
                  if (typeof(TValue) == typeof(string))
                  {
                      CurrentValue = (TValue)(object)value;
                  }
                  else if (typeof(TValue) == typeof(int))
                  {
                      int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var parsedValue);
                      CurrentValue = (TValue)(object)parsedValue;
                  }
                  else if (typeof(TValue) == typeof(int?))
                  {
                      if (value == null)
                      {
                          CurrentValue = (TValue)(object)null;
                      }
                      else
                      {
                          int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsedValue);
                          CurrentValue = (TValue)(object)parsedValue;
                      }
                  }
              }
          }
      
    • js:

    window.select2Component = {
            init: function (Id) {
                //Initialize Select2 Elements
                $('#' + Id).select2();
            },
            onChange: function (id, dotnetHelper, nameFunc) {
                $('#' + id).on('select2:select', function (e) {
                    dotnetHelper.invokeMethodAsync(nameFunc, $('#' + id).val());
                });
            },
        }

    【讨论】:

    • 你在某处有完整的例子吗?
    • 它甚至无法编译。
    猜你喜欢
    • 1970-01-01
    • 2022-11-07
    • 2023-02-24
    • 2019-10-01
    • 2021-07-29
    • 1970-01-01
    • 2013-02-24
    • 2020-01-15
    • 2021-02-25
    相关资源
    最近更新 更多