Blazor jQuery select2两种方式绑定

时间:2019-12-01 08:08:26

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

我在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>

1 个答案:

答案 0 :(得分:0)

我用select2库为blazor创建了一个自定义组件select。 我希望这是您的榜样。 -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());
            });
        },
    }