You can create a Javascript function to change the selected option, then in the Clear button click event, call the JavaScript function.
In the _Host.cshtml or _Layout.cshtml page, add the following JavaScript function in the head section:
<script>
window.clearSelect = function(elename){
document.getElementById(elename).value = "0";
}
</script>
Then in the view component, use the InvokeVoidAsync method to call the JavaScript function. code like this:
@page "/ddltest"
@inject IJSRuntime JS
<h3>DropDownTest</h3>
<div class="col-md-4 col-lg-3">
<div style="align-items: center;display:flex;flex-direction: row;">
<div style="display:flex; flex-direction: row; align-items: center;">
<span class="text-sm mb-0 text-capitalize font-weight-bold required" style="width:150px;margin-top:-50px;">Database Name</span>
  
<select id="ddldatabase" class="form-select" @onchange="SelecteddatabaseChanged"
style="width:300px;margin-left:-20px;height:100px;" multiple>
@if (databasenames.Any())
{
<option value="0">--Select--</option>
@foreach (var serv in databasenames)
{
<option value="@serv.databaseName">
@serv.databaseName
</option>
}
}
</select>
</div>
</div>
</div>
<button type="button" class="btn btn-primary" style="width:140px;color: #fff !important;background-color:#ccc !important;" @onclick="Clear">
Clear
</button>
@code {
private IEnumerable<DatabaseClass> databasenames = Array.Empty<DatabaseClass>();
private ApplicationsData appsdata = new ApplicationsData();
private string[] Selecteddatabase { get; set; }
private ElementReference ddl;
public class DatabaseClass
{
public int databaseId { get; set; }
public string databaseName { get; set; }
}
public class ApplicationsData
{
public string DatabaseList { get; set; }
}
protected override async Task OnInitializedAsync()
{
databasenames = new List<DatabaseClass>()
{
new DatabaseClass(){ databaseId=101, databaseName="datawarhous"},
new DatabaseClass(){ databaseId=101, databaseName="meno"},
new DatabaseClass(){ databaseId=101, databaseName="review data"},
new DatabaseClass(){ databaseId=101, databaseName="manhaten"},
};
}
private void SelecteddatabaseChanged(ChangeEventArgs e)
{
if (e.Value is not null)
{
Selecteddatabase = (string[])e.Value;
string concatevalue = string.Join(", ", Selecteddatabase);
appsdata.DatabaseList = concatevalue;
}
}
public async void Clear()
{
Selecteddatabase = Array.Empty<string>();
appsdata.DatabaseList = "";
//call the javascript function and transfer the select element's id to the javascript function.
await JS.InvokeVoidAsync("clearSelect", "ddldatabase");
}
}
The result as below:
Refer : Call JavaScript functions from .NET methods in ASP.NET Core Blazor
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion