Search code examples
parameterscomponentsblazor

Blazor 3.1 Component Tag Helper parameters


I'm trying to pass parameters into a Blazor component on a razor page using the new tag helper in 3.1 and it works with an integer type, but if I change to a string string it throws a error. What am I missing?

Component:

<p>Test Parameter: @TestParameter</p>

@code {
  [Parameter]
  public int TestParameter { get; set; }

}

Razor page:

@page "/test"
@model BlazorTest.testModel
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>test</title>
</head>
<body>

  <component type="typeof(TestComponent)" render-mode="ServerPrerendered" param-TestParameter="20" />

  <script src="~/_framework/blazor.server.js"></script>
</body>
</html>

Changing Component to below causes:

InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'.

<p>Test Parameter: @TestParameter</p>

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

}

Solution

  • You should do this:

     <p>Test Parameter: @TestParameter</p>
    
    @code {
        [Parameter]
        public string TestParameter { get; set; }
    
    }
    

    And this:

    <app>
            @{
                var val = "Hello world";
            }
            <component type="typeof(TestComponent)" render-mode="ServerPrerendered" param-TestParameter="@(val)" />
        </app>
    

    This is only an educated guess that you should define a variable of the type you want with var, and then let it be evaluated in Razor expression. Thus, if your parameter property is passed an integer, you should have it like this:

      @{
            var val = 120;
       }