Binding the value of a HTML element to a C# property in Blazor

asp.net-core blazor c#

Question

In the blazor application that I am building, I have the following cshtml code which containts a <input> element for the user to enter their name. I want to be able to bind the value of the input element to the Name property in the c# functions section of the blazor page.

How would I do that?

My code is as follows:

  @page "/nameUpload"

  <p>
 //This is the input element that I would like to bind
Enter your name: <input type="text" ><br />
  </p>

  @functions {
  //This is the property that I want to bind the input to
  private string Name { get; set; } = "";
 }

Accepted Answer

Use the @bind attribute with an input.

@page "/nameUpload"

<p>
    @* This is the input element that I would like to bind *@
    Enter your name: <input type="text" @bind(name) />
    <br />
</p>

@functions {
    @* This is the property that I want to bind the input to *@
    string name;
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why