ASP.NET Core 5.0 : MVC, Razor Pages, Web API, EF Core, Blazor, Design Patterns, and more. Private online coaching for software developers. Click here for more details.

Pass Parameters to Blazor Components

Blazor apps consist of one or more components. A component can receive data from an external source through parameters. In this article you will learn to add parameters to a Blazor component. You will also learn various ways of setting the parameter values.

Begin by creating a new Blazor Server App project in Visual Studio.

Then right click on the Pages folder and select Add New Item menu option. Add a new Razor Component named Message.razor to the Pages folder.

The Message component is intended to display a message onto a page. Write the following markup and code in the Message.razor file.

<h1>@Value</h1>

@code {

    string Value { get; set; }

    protected override void OnInitialized()
    {
       Value = "Hello World!";
    }
}

Here, we created Value property in the component and set it's value to Hello World! in the OnInitialized() method.

We will house this component on the Index page. To do so, open Index.razor from Pages folder and write the following markup.

<Message></Message>

If you run the application, you will see the message displayed on the page.

The second Hello World! message is from our Message component.

Now, let's accept this message from Index component (where we have housed the Message component) by creating a Value parameter.

Modify Message.razor as shown below:

h1>@Value</h1>

@code {
    [Parameter]
    public string Value { get; set; }
}

Notice that the Value property is decorated with [Parameter] attribute. Moreover, it is now made public. The [Parameter] attribute indicates that the underlying property is a component parameter.

To set this parameter from the Index component, change the markup as shown below:

<Message Value="Hello Universe!"></Message>

This time we pass the message Hello Universe! to the Message component through the Value parameter. And the result is this:

The Message component created above is housed inside the Index component. However, you can also make it behave like a standalone page by adding @page directive. The following code shows how.

@page "/Message"

Now the Message component can be accessed by entering /Message in the browser's address bar.

It is also possible to pass a parameter value from route rather than setting it in the component's markup. To do so, you need to add a route parameter like this:

@page "/Message/{value}"

Here, we added a route parameter called value. Modify the component markup to:

<Message></Message>

Now run the app and enter /Messahe/Hello Galaxy in the address bar. You should get this outcome:

That means our Value parameter is now mapped to a route value.

What if you wish to map a query string parameter to a component parameter? There is no direct way to accomplish this. But you can do that through code. Let's see how.

First, inject NavigationManager object into the Message component by writing this below the @page directive.

@inject NavigationManager NavigationHelper

This line will inject NavigationManager object that can be accessed in the code through NavigationHelper property.

Also import Microsoft.AspNetCore.WebUtilities namespace because we will be using QueryHelpers class from this namespace.

@using Microsoft.AspNetCore.WebUtilities

Next, add this code to OnInitialized() method.

protected override void OnInitialized()
{
    var uri = NavigationHelper.ToAbsoluteUri
(NavigationHelper.Uri);

    if (QueryHelpers.ParseQuery(uri.Query).
TryGetValue("Value", out var value))
    {
        Value = value.First();
    }
}

This code parses the query string and tries to grab the Value query string parameter. If found, its value is assigned to the Value component property.

Since we aren't using Value property as a parameter here, you can remove or comment out the [Parameter] attribute.

string Value { get; set; }

Run the app and assign Values query string as shown below:

What if you want to pass a list of messages from external world to the Message component? There are couple of ways to accomplish that.

Let's create another component called MessageList to demonstrate those.

Add a new Razor Component named MessageList.razor to the Pages folder. Write the following code to it.

<ul>
    @foreach(var item in Items)
    {
        <li>@item</li>
    }
</ul>

@code {

    [Parameter]
    public string Values { get; set; }

    List<string> Items { get; set; }

    protected override void OnInitialized()
    {
        Items = Values.Split(',').ToList();
    }
}

Here, we created a parameter called Values. It is assumed that multiple values will be passed as a comma separated string. So, OnInitialized() method splits the Values parameter and stores them into a List of strings. The List<string> is outputted as a bulleted list using a foreach loop.

Here is how you can use the MessageList component in the Index onent.

<MessageList 
  Values="Hello World!,Hello Galaxy!,Hello Universe!">
</MessageList>

And here is the output:

Other way is to store messages into a List and design Values to be a List<string>

<ul>
    @foreach (var item in Values)
    {
        <li>@item</li>
    }
</ul>
[Parameter]
public List<string> Values { get; set; }

Since Values is now a List<string> you can't assign it as a comma separated values. So, add this code to Index component.

<MessageList Values="@values"></MessageList>

@code{

    List<string> values = new List<string>() {
        "Hello World!",
        "Hello Galaxy!",
        "Hello Universe!"
    };
}

We store messages into a List and then set the Values parameter to @values. The outcome will be same as in the previous example.

In this article you learned to add parameters to Blazor components. However, there is more to Blazor's parameter story. We will learn more about that in the next article.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get connected : Facebook  Twitter  LinkedIn  YouTube

Posted On : 29 December 2020


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates