How to use html dropdown in Blazor



While working on a Blazor project, so many times we will use plain HTML dropdown. In this scenario, we will get a requirement to trigger the event and reset the selection item to the initial state.

Here are some code snippets for completing this task.

Approach 1:

@page "/counter"

<select @onchange="OptionChanged" value="@selectedOption">
    <option value="-1">Select Option</option>
    @foreach (var option in options)
    {
        <option value="@option">@option</option>
    }
</select>

<button @onclick="ClearSelection">Clear Selection</button>

@code {
    private List<string> options = new List<string> { "Option 1", "Option 2", "Option 3" };
    private string selectedOption { get; set; } = "-1"; // Set default value to "-1"

    private void OptionChanged(ChangeEventArgs e)
    {
        // Extract the selected value from the event argument
        string selectedValue = e.Value.ToString();
        Console.WriteLine($"Selected option: {selectedValue}");
        // Assign the selected value to the selectedOption variable
        selectedOption = selectedValue;
    }

    private void ClearSelection()
    {
        // Clear the selected option
        selectedOption = "-1"; // Reset to default value "-1"
        StateHasChanged(); // Trigger a UI update
    }
}

Approach 2:

@page "/"

<PageTitle>Home</PageTitle>

<select @onchange="OptionChanged" value="@selectedOption">
    <option value="">Select Option</option>
    @foreach (var option in options)
    {
        <option value="@option">@option</option>
    }
</select>

<button @onclick="ClearSelection">Clear Selection</button>

@code {
    private List<string> options = new List<string> { "Option 1", "Option 2", "Option 3" };
    private string selectedOption { get; set; } = "";

    private void OptionChanged(ChangeEventArgs e)
    {
        // Extract the selected value from the event argument
        string selectedValue = e.Value.ToString();
        Console.WriteLine($"Selected option: {selectedValue}");
        // Assign the selected value to the selectedOption variable
        selectedOption = selectedValue;
    }

    private void ClearSelection()
    {
        // Clear the selected option
        selectedOption = "";
        // Trigger a UI update
        StateHasChanged();
    }
}

Summary:

In this code snippet, we demonstrate how to handle various scenarios using an HTML dropdown in Blazor.

Http CRUD Operation in Azure Function with C# (Part 3)


This is part 3 blog post of azure function. If you have not read previous post. Please read from here.

In this demo, for shake of simplicity, we will create dummy employee collection data and perform CRUD operation.

Step 1: Create the Employee class in model folder like this.

namespace HelloAzureFunction.Model
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Salary { get; set; }
    }
}

Step 2: Create the Http trigger Employee Function with Anonymous AuthorizationLevel and write the method for Get, Post, Put and Delete method like this

Post Method

private readonly List<Employee> employeeDataStore = new List<Employee>();
private readonly ILogger _logger;

public EmpFunction(ILoggerFactory loggerFactory)
{
    _logger = loggerFactory.CreateLogger<EmpFunction>();
    InitializeDummyData();
}

// Initialization method to populate dummy data
private void InitializeDummyData()
{
    employeeDataStore.Add(new Employee { Id = 1, Name = "John Doe", Salary = 50000 });
    employeeDataStore.Add(new Employee { Id = 2, Name = "Jane Smith", Salary = 60000 });
    employeeDataStore.Add(new Employee { Id = 3, Name = "Anvi Sah", Salary = 70000 });
}

//Post Method
[Function("CreateEmployee")]
public HttpResponseData CreateEmployee(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestData req)
{
    _logger.LogInformation("CreateEmployee function processed a request.");

    var requestBody = req.ReadAsStringAsync().Result;
    var newEmployee = JsonSerializer.Deserialize<Employee>(requestBody);

    // Need to Store in actual database
    employeeDataStore.Add(newEmployee);

    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Headers.Add("Content-Type", "application/json; charset=utf-8");

    response.WriteString(JsonSerializer.Serialize(newEmployee));

    return response;
}

GET Method

//Get Method
[Function("GetAllEmployees")]
public HttpResponseData GetAllEmployees(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequestData req)
{
    _logger.LogInformation("GetAllEmployees function processed a request.");

    var response = req.CreateResponse(HttpStatusCode.OK);
    response.Headers.Add("Content-Type", "application/json; charset=utf-8");

    response.WriteString(JsonSerializer.Serialize(employeeDataStore));

    return response;
}

PUT Method

//PUT Method
[Function("UpdateEmployee")]
public HttpResponseData UpdateEmployee(
    [HttpTrigger(AuthorizationLevel.Anonymous, "put")] HttpRequestData req)
{
    _logger.LogInformation("UpdateEmployee function processed a request.");

    var requestBody = req.ReadAsStringAsync().Result;
    var updatedEmployee = JsonSerializer.Deserialize<Employee>(requestBody);

    // Find and update the employee based on Id
    var existingEmployee = employeeDataStore.Find(e => e.Id == updatedEmployee.Id);
    if (existingEmployee != null)
    {
        existingEmployee.Name = updatedEmployee.Name;
        existingEmployee.Salary = updatedEmployee.Salary;
    }

    var response = req.CreateResponse(HttpStatusCode.OK);
    response.WriteString("Employee updated.");

    return response;
}

Delete Method

 //Delete Method
 [Function("DeleteEmployee")]
 public HttpResponseData DeleteEmployee(
     [HttpTrigger(AuthorizationLevel.Anonymous, "delete")] HttpRequestData req)
 {
     _logger.LogInformation("DeleteEmployee function processed a request.");

     var requestBody = req.ReadAsStringAsync().Result;
     var employeeIdToDelete = JsonSerializer.Deserialize<Employee>(requestBody);

     // Find and remove the employee based on Id
     var employeeToDelete = employeeDataStore.Find(e => e.Id == employeeIdToDelete.Id);
     if (employeeToDelete != null)
     {
         employeeDataStore.Remove(employeeToDelete);
     }

     var response = req.CreateResponse(HttpStatusCode.OK);
     response.WriteString("Employee deleted.");

     return response;
 }

Now run the application and test on postman.

Summary

In the above demo, we saw that how easily we are able to create RESTful APIs with the help of HTTP Trigger.

Source Code

https://github.com/Chandradev819/HelloAzureFunction.git

Cascading Values & Cascading Parameters in Asp.net core Blazor


Today i was working on one blazor POC project, there i got a requirement to pass some value to all the child components which one i was using on the parent component.

Then i found one of the best approach to pass in all the child component using Cascading Values & Cascading Parameters

Let see this concept one small example.

Step 1: Create the parent component like this

@page "/home"

<CascadingValue Value="@FirstFruit" IsFixed="true" Name="FirstFruit">
    
        <Fruit></Fruit>
    
</CascadingValue>

@code {
    string FirstFruit { get; set; } = "Apple";
    
}

In the above code, i m passing FirstFruit property to all the child component, There could be multiple child component. For simplicity i have taken only one.

IsFixed=”true” means Blazor will not monitor it for changes. It is good practice to improve the performance when there will be multiple child component.

Step 2: Create the Fruit Component like this.

<h5>Demo for Cascading Value and Cascading Parameter</h5><br />

<p>The fruit Name is: @Name </p>

@code {
    [CascadingParameter(Name = "FirstFruit")] 
    string Name { get; set; }
}

In the above code CascadingParameter means which field will receive the Cascading Value.
(Name = “FirstFruit”): Means which field we are going to bind from parent component.

Summary

In this sample we saw that how pass the value from parent component to multiple child component with a very minimal coding.

QueryString in Asp.net Core Blazor


Querystring is generally used for passing data from one page to other page. But in Asp.net Core Blazor very straight forward to read the query string.

Step 1: Create the page from where you will pass the query string data. I have created in index page like this.

@page "/"

<h3>Query string Demo</h3>
<a href="/querystringpage?a=2&b=4">Click Here</a> <br />


<br />
<form action="querystringpage">
    First Num1 : <input name="a" /> 
    Second Num2 : <input name="b" />
    <input type="submit" />
</form>

Step 2: Create the page where you are going to read the query string data.

@page "/querystringpage"
@inject NavigationManager nav
@using Microsoft.AspNetCore.WebUtilities

URI: @uri;
<br />

Num1 :@a <br />
Num2 :@b <br />
Sum of Two Num: <b>@c</b>


@code {
    System.Uri uri;
    int a;
    int b;
    int c;
    protected override void OnInitialized()
    {
        uri = nav.ToAbsoluteUri(nav.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("a", out var aVal))
        {
            a = int.Parse(aVal);
        }
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("b", out var bVal))
        {
            b = int.Parse(bVal);
        }
        c = a + b;
    }

}

In the above code, we saw that we are using Microsoft.AspNetCore.WebUtilities namespace, which has the helper method i.e. QueryHelpers to extract the query string value. We have also injected the NavigationManager the url path of page.

Summary:

In this small demo, we saw that how QueryHelpers method of Microsoft.AspNetCore.WebUtilities namespace simplified our code to read the query string in asp.net core Blazor.

Data binding in Asp.net Core Blazor


There are two type of data binding in asp.net core blazor

1. One way data binding
2. Two way data binding

One way data binding

In this approach data communication will happen in one way. In blazor case data will be bind from the component class to the component view.

Example of one way data binding

@page "/oneway"
<h3>One way Data binding Example</h3> <br />

 Message: @msg 

@functions {
    string msg = "This is one ways data binding message.";
}

Two way data binding

In this approach data can pass in both ways. We can use this type of data binding on text-box to label or text-box depending on our requirement.

Example of Two way data binding

@page "/twoWay"
<h3>Two-way Data Binding Example</h3>

    Enter your name:
<input @bind=@Name   @bind:event="oninput" />
<br />
<br />
    Is it intresting to Learn Blazor ?
<input type="checkbox" @bind="IsTry" />
<br />
<br />
<br />

<p><b>Summary</b></p>
    You have entered:@Name
    <br />
    Your Answer: @(IsTry ? "Yes" : "No")

    @functions {
        public string Name { get; set; }
        public bool IsTry { get; set; }
    }  

Summary
In this small post we saw the example of data-binding in Blazor.