Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

.net core - Blazor parameter With Null value

We have a Blazor Server app core 3.1 , we add a component and call it from navigation like this

<a href="/Claimaction" class="nav-link">
                        <i class="far fa-circle nav-icon"></i>
                        <p>Claims</p>
                    </a>

is some time i want to reach this component by other one with parameter like "/Claimaction/PId" and i want to set this parameter directly by input from component itself but when call the component from NAV without parameter value the component set Sorry, there's nothing at this address. how to solve this issue to allow user set parameter value with three way

  1. by Nav like "/Claimaction/100001"
  2. by component Input Control
  3. Allow open component with Null parameter value
question from:https://stackoverflow.com/questions/65878958/blazor-parameter-with-null-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think what you are looking for is an optional Route parameter.

Since .Net5, optional route parameters exist natively. Just add a ? at the end of the parameter.

@page "/Claimaction/{ClaimsId:int}"
@* if navigation without id, should be possible, this route is needed too  *@
@page "/Claimaction"
  
@* for .NET 5 only on @page directive is needed
    @page "/Claimaction/{ClaimsId:int?}"
*@

@code{

  [Parameter]
  public Int32? ClaimsId { get; set; }

  public override async Task OnParametersSetAsync()
  {
        await base.OnParametersSetAsync();
        ClaimsId = ClaimsId ?? -1; // set default value if not set via routing or input
  }

}


Because the ClaimsId has the name as the router parameter {ClaimsId:int}, it is bound when used via Url like /ClaimsAction/10235 (Way 1)

Because ClaimsId is a Parameter you can set it via binding or any other way. (Way 2). Even if a @page directive exists, you could still use it as a "normal" component nested inside other components or your layout.

Because ClaimsId is a nullable type, it doesn't require a value at all. If no value is received either via routing or input, the value will be set to -1. To achieve this behavior, we override SetParamterAsync and set a default value there ( ClaimsId = ClaimsId ?? -1;).

I would recommend reading this tutorial too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...