I cannot for the life of me figure out what the correct syntax is for binding a class member to an attribute. Specifically in this case the href attribute for an tag or Blazor's tag.
What I am trying to do is this, equivalent example with Vue.js
<a :href="'/customers/' + customer.CustomerID">
How do I do this in Blazor component?
I've tried:
<a @bind-href="/customers/customer.CustomerID">
<a @bind-href="/customers/@customer.CustomerID">
<a href="/customers/customer.CustomerID">
<a href="/customers/@customer.CustomerID">
Nothing works. CustomerID is of int type.
When using the NavLink component (instead of a <a>
Tag), you have to use:
href="@($"customer/{customer.CustomerID}")"
Suppose we've defined a Blazor Component named Customer, and we want to call it from the Index page component. You can place an anchor element in the the Index component as follow:
<a href="customer/@customer.CustomerID">Click me</a>
The value of the href attribute is a url made of two segments: 1. customer which stands for the name of the component. Note that it should not be preceded with "/"
<a href="customer/1">Click me</a>
Below is the definition of the Index component Index.razor:
@page "/"
<a href="customer/@customer.CustomerID">Click me</a>
<a href="customer/2">Click me</a>
@code
{
Customer customer = new Customer();
public class Customer
{
public int CustomerID { get; set; } = 1;
public string Name { get; set; } = "Microsoft";
}
}
The following is the definition of the Customer component Customer.razor:
@page "/customer"
@page "/customer/{CustomerID:int}"
<p>@CustomerID</p>
@code {
[Parameter]
public int CustomerID { get; set; }
}
Note that the Customer component contains two @page directives with route templates. The first directive is used when you want to route to the component without providing a customer ID, as for instance:
<a href="customer">Click me</a>
The second route template is used when you want to route to the Customer component with CustomerID parameter. Note also that the Customer component contains a public property with a Paramater attribute. This property is populated by Blazor with the parameter passed to the Customer component when it is routed to.
Your unsuccessful attempts to set the href attribute of the anchor element clearly stems from the simple fact that you are not familiar with the Routing system of Blazor, so here is a link to the docs about Blazor routing... Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With