Search code examples
c#datedatetimeblazorblazor-webassembly

Disable specific dates in Blazor


I have some fields in my editform. So here based on my Transport dropdown value selection , shipping date(Datetime) should disable the dates in its calendar. So here is goes.

 <div class="form-group col">
  <label>Main Transport</label>
    @if (lstTransports != null)
      {
         <InputSelect id="txtMainTransport" class="form-control" @bind-Value="@trade.transport" @onchange="OnMainTransportValueChange">
         <option selected value="-1">-Select-</option>
         @foreach (var transport in lstTransports)
           {
              <option value="@transport.id">@transport.id</option>
           }
          </InputSelect>
          <ValidationMessage For="@(() => trade.transport)" />
         }
 </div>

   <div class="form-group col">
         <label>Estimated Shipping Date</label>
            <InputDate id="shippingDate" @bind-Value="@trade.shippingDate" @bind-Value:format="dd/mm/yyyy"  class="form-control" />
            <ValidationMessage For="@(() => trade.shippingDate)" />
       </div>

here is the onchange function:

private async void OnMainTransportValueChange(ChangeEventArgs e)
        {
            trade.transport= e.Value.ToString();
            if(trade.transport == "Sea")
            {
                //here it should have my date disable code
                
            }
        }

Now in onchange based on Transport value i want to disable by Shipping date Calendar dates. So if Transport == Sea then the dates less than Datetime.Today.AddDays(5)in shipping date calendar should be disabled.

How can i handle it in c# ? I tried to modify by shipping date id but it doesn't seem to detect the id value. Please help.


Solution

  • This worked for me

        <InputDate @bind-Value="@myClass.shippingDate" @attributes="@shippingDateAttributes"  />
    

    ...

    @code {
        Dictionary<string, object>? shippingDateAttributes = new();
    
    private async void OnMainTransportValueChange(ChangeEventArgs e)
            {
                trade.transport= e.Value.ToString();
                if(trade.transport == "Sea")
                {
                    //here it should have my date disable code
                    string maxDate = (DateTime.Now + TimeSpan.FromDays(5)).ToString("yyyy-MM-dd");
                    shippingDateAttributes.Add("max", maxDate);
                   StateHasChanged();
                }
            }
       }
    

    You need also some logic to make sure you don't add the attribute twice. So ideally you would remove the 'max' attribute first before you add it.

    Here is a reference I used for this post: Disable Dates for DateTime picker