mohandes
mohandes

Reputation: 137

How to create a html form with clicking on a button in blazor? Is there any way to do that without javascript? if so how? if not how?

<button onclick="createForm">create form</button>
<form >
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" value="Submit">
</form> 

I want to create form when I click on button create form. at the start no form will appear. just when the button create form is clicked.

Upvotes: 1

Views: 1760

Answers (1)

Farjad Zaman
Farjad Zaman

Reputation: 171

The easiest way you can do this is that you can hide the form and show it on the click event of the button. You can do that with simple Razor Markup.

   <button onclick="createForm">create form</button>
    @if(IsFormVisible)
   {
      <form >
        <label for="fname">First name:</label><br>
        <input type="text" id="fname" name="fname" value="John"><br>
        <label for="lname">Last name:</label><br>
        <input type="text" id="lname" name="lname" value="Doe"><br><br>
        <input type="submit" value="Submit">
     </form> 
   }
@code
{
   bool IsFormVisible = false;
   void createForm()
   {
     IsFormVisible = true;
     StateHasChanged();
   }
}

The second way that you can do it (and this might be an overkill) is by using DynamicComponent which came with .NET 6. Basically, you can just create any component and pass that as a parameter to DynamicComponent and it will render the component which you passed to it. You can create a Blazor component with a form and then pass that component on button click event to DynamicComponent like this:

<DynamicComponent Type="@YourFormComponent"/>

You can refer to Dave Brock's article for details: https://www.daveabrock.com/2021/04/08/blazor-dynamic-component/

Upvotes: 2

Related Questions