How to create component in blazor ?

 

What is a component in blazor?

In Blazor components are basically classes that interact with the .razor file of the component,
which gets displayed on the browser.


  • Blazor components are HTML template that declares what renders on the page.

    In this tutorial we are going to render  list of student.
    Here are the some steps to create blazor components, let's get started

1. Create a fresh new blazor inside component folder 
        I. open cmd and type mkdir component


2. Then, open folder with component folder (code .)

    

3. Open code terminal by pressing ( ctrl + . ) or goto terminal and click new terminal



4. Goto terminal and type (dontnet new blazorserver)



5. Expand sidebar and you can see following structure


6. Create folder inside Pages with name student Inside student foler create file DemoStudent.razor file

            

📁

Pages
                   

📁

student
                           DemoStudent.razor
7. Create folder inside student with name components inside components create new file name List.razor
      

📁

Pages
                   

📁

student
                                

📁

components
                                        List.razor
                         DemoStudent.razor




8. Create Models folder in root directory inside models create file name Student.cs
which  is modal class which we use in our component. Student modal has two property 
Id and Name.


    Source Code

    namespace component.Models
    {
        public class Student
        {
            public int Id { getset; }
            public string Name { getset; }
        }
    }


9. In DemoStudent.razor file write following code 


OnInitialized is the function which is invoked when the component is initilized.

To use <List Student="@student"></List> we should import Student Modal and components in _Import.razor.

_Import.razor



    @using System.Net.Http
    @using Microsoft.AspNetCore.Authorization
    @using Microsoft.AspNetCore.Components.Authorization
    @using Microsoft.AspNetCore.Components.Forms
    @using Microsoft.AspNetCore.Components.Routing
    @using Microsoft.AspNetCore.Components.Web
    @using Microsoft.AspNetCore.Components.Web.Virtualization
    @using Microsoft.JSInterop
    @using component
    @using component.Pages.student.components
    @using component.Shared
    @using component.Models



10. Inside List.razor file paste following code




    <div class="card p-2 mb-3 shadow-sm border-0">
        <h5>Id : @Student.Id</h5>
        <h5>Name : @Student.Name</h5>
        
    </div>
        @code{
            [Parameter]
            public Student Student { getset; }
        }




11. Finally remove everything written in index.razor and make blank

finally type dotnet watch run following output will render.












Reactions

Post a Comment

0 Comments