Blog

  • How Blazor works

    Blazor provides many features to help you get started and deliver your next web app project fast. Let’s take a tour of the core capabilities of Blazor to help you decide whether you should use Blazor for your next great web app.

    Blazor components

    Blazor apps are built from components. A Blazor component is a reusable piece of web UI. A Blazor component encapsulates both its rendering and UI event handling logic. Blazor includes various built-in components for form handling, user input validation, displaying large data sets, authentication, and authorization. Developers can also build and share their own custom components, and many prebuilt Blazor components are available from the Blazor ecosystem.

    Use standard web technologies

    You author Blazor components using Razor syntax, a convenient mixture of HTML, CSS, and C#. A Razor file contains plain HTML and then C# to define any rendering logic, like for conditionals, control flow, and expression evaluation. Razor files are then compiled into C# classes that encapsulate the component’s rendering logic. Because Blazor components authored in Razor are just C# classes, you can call arbitrary .NET code from your components.

    UI event handling and data binding

    Interactive Blazor components can handle standard web UI interactions using C# event handlers. Components can update their state in response to UI events and adjust their rendering accordingly. Blazor also includes support for two-way data binding to UI elements as a way to keep component state in sync with UI elements.

    The following example is a simple Blazor counter component implemented in Razor. Most of the content is HTML, while the @code block contains C#. Every time the button is pressed the IncrementCount C# method is invoked, which increments the currentCount field, and then the component renders the updated value:

    razorCopy

    <h1>Counter</h1>
    
    <p role="status">Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
    
        private void IncrementCount()
        {
            currentCount++;
        }
    }

    https://lernix.com.my/about

  • What is Blazor?

    Blazor is a modern frontend web framework based on HTML, CSS, and C# that helps you build web apps faster. With Blazor, you build web apps using reusable components that can be run from both the client and the server so that you can deliver great web experiences. Blazor is part of .NET, a developer platform for building anything. .NET is free, open-source, and runs cross-platform.

    Some of the benefits of using Blazor include:

    • Build web UI fast with reusable components: Blazor’s flexible component model makes it easy to build reusable components that you can use to assemble apps quickly.
    • Add rich interactivity in C#: Handle arbitrary UI events from the browser and implement component logic all in C#, a modern type-safe language that is easy to learn and highly versatile.
    • One development stack: Build your entire web app from the frontend to the backend using a single development stack and share code for common logic on the client and server.
    • Efficient diff-based rendering: As components render, Blazor carefully tracks what parts of the DOM changed, so that UI updates are fast and efficient.
    • Server and client-side rendering: Render components from both the server and the client to implement various web app architectures and deliver the best possible web app experience.
    • Progressively enhanced server rendering: Use built-in support for enhanced navigation & form handling and streaming rendering to progressively enhance the user experience of server rendered web apps.
    • Interop with JavaScript: Use the ecosystem of JavaScript libraries and browser APIs from your C# code.
    • Integrate with existing apps: Integrate Blazor components with an existing MVC, Razor Pages, or JavaScript based apps.
    • Great tooling: Use Visual Studio or Visual Studio Code to get started in seconds and stay productive with great code editing support.
    • Web, mobile, and desktop: Blazor components can also be used to build native mobile & desktop apps using a hybrid of native and web, called Blazor Hybrid.

    https://lernix.com.my/affiliation

  • Understand tag helpers and page handlers

    In the previous unit, you created a Razor Page that displays a list of pizzas. You used the @ symbol to switch contexts between HTML and C#. In this unit, you’ll learn about tag helpers. Tag helpers are a special kind of HTML element that can contain C# code. You’ll also learn about page handlers. Page handlers are methods that handle browser requests. You’ll use page handlers in the next unit to add and delete pizzas.

    Tag helpers

    Tag helpers are used to address the inefficiencies of context switching between HTML and C#. Most of ASP.NET Core’s built-in Tag helpers extend standard HTML elements. Tag helpers provide extra server-side attributes for HTML elements, making the elements more robust.

    There are four tag helpers you should know for this project: PartialLabelInput, and Validation Summary Message.

    Partial Tag Helper

    CSHTMLCopy

    <partial name="_ValidationScriptsPartial" />
    

    This injects the contents of the _ValidationScriptsPartial.cshtml file into a page. The _ValidationScriptsPartial.cshtml file contains JavaScript that’s used to validate form input, so it needs to be included on every page that contains a form.

    Label tag helper

    CSHTMLCopy

    <label asp-for="Foo.Id" class="control-label"></label>
    

    This extends the standard HTML <label> element. Like many tag helpers, it uses an asp-for attribute. The attribute accepts a property from the PageModel. In this case, the name of the PageModel‘s Foo.Id property (specifically, the string "Id") will be rendered as the content for an HTML <label> element.

    Input tag helper

    CSHTMLCopy

    <input asp-for="Foo.Id" class="form-control" />
    

    Similar to the previous example, this extends the standard HTML <input> element. It also uses an asp-for attribute to specify a PageModel property. In this case, the value of the Foo.Id property will be rendered as the value attribute for an HTML <input> element.

    Validation Summary Tag Helper

    CSHTMLCopy

    <div asp-validation-summary="All"></div>
    

    The Validation Summary Tag Helper displays a validation message for a single property on the model.

     Note

    Things like validation rules and property display names are defined in the PageModel class. We’ll point out where to find them in the code in the next unit.

    Page handlers

    The PageModel class defines page handlers for HTTP requests and data used to render the page. In the previous exercise, the PizzaListModel class handled the HTTP GET request by setting the value of the PizzaList property to the value of _service.GetPizzas().

    Common handlers include OnGet for page initialization and OnPost for form submissions. To handle an HTTP POST, a page handler might verify the user-submitted data, present the input form page again if invalid, or send the valid data to a service or database for persistence.

    In the next unit, you’ll add a form to create new pizzas using several tag helpers. You’ll also add page handlers to handle the form submission and deletion of pizzas.

    https://lernix.com.my/rooms

  • Understand when and why to use Razor Pages

    In this unit, you’ll learn when and why to use Razor Pages for your ASP.NET Core app.

    The benefits of Razor Pages

    Razor Pages is a server-side, page-centric programming model for building web UIs with ASP.NET Core. Benefits include:

    • Easy setup for dynamic web apps using HTML, CSS, and C#.
    • Organized files by feature for easier maintenance.
    • Combines markup with server-side C# code using Razor syntax.

    Razor Pages utilize Razor for embedding server-based code into webpages. Razor syntax combines HTML and C# to define the dynamic rendering logic. This means you can use C# variables and methods within your HTML markup to generate dynamic web content on the server at runtime. It’s important to understand that Razor Pages are not a replacement for HTML, CSS, or JavaScript, but rather combines these technologies to create dynamic web content.

    Separation of concerns

    Razor Pages enforces separation of concerns with a C# PageModel class, encapsulating data properties and logic operations scoped to its Razor page, and defining page handlers for HTTP requests. The PageModel class is a partial class that is automatically generated by the ASP.NET Core project template. The PageModel class is located in the Pages folder and is named after the Razor page. For example, the PageModel class for the Index.cshtml Razor page is named IndexModel.cs.

    When to use Razor Pages

    Use Razor Pages in your ASP.NET Core app when you:

    • Want to generate dynamic web UI.
    • Prefer a page-focused approach.
    • Want to reduce duplication with partial views.

    Razor Pages simplifies ASP.NET Core page organization by keeping related pages and their logic together in their own namespace and directory.

    https://lernix.com.my/careers

  • Data binding and events

    Let’s explore how to define component rendering logic and handle UI events.

    Render C# expression values

    When you want to render the value of a C# expression in Razor, you use a leading @ character. For example, a Counter component can render the value of its currentCount field like this:

    razorCopy

    <p role="status">Current count: @currentCount</p>
    

    Razor can typically figure out when a C# expression ends and you transition back to writing HTML. But you can also be explicit about the beginning and ending of the expression using parens.

    razorCopy

    <p role="status">Current count: @(currentCount)</p>
    

    Add control flow

    You can add control flow to your component rendering logic using normal C# statements. For example, you can conditionally render some content using a C# if-statement, like this:

    razorCopy

    @if (currentCount > 3)
    {
        <p>You win!</p>
    }
    

    You can also use C# to loop over data and render a list of items:

    razorCopy

    <ul>
        @foreach (var item in items)
        {
            <li>@item.Name</li>
        }
    </ul>
    

    Handle events

    Blazor components often handle UI events. To specify an event callback for an event from a UI element, you use an attribute that starts with @on and ends with the event name. For example, you can specify the IncrementCount method as a handler for a button click event using the @onclick attribute, like this:

    razorCopy

    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    

    You can specify C# event handlers for other HTML events too, like @onchange@oninput, and so on. Event handling methods can be synchronous or asynchronous. You can also define event handlers inline using C# lambda expressions:

    razorCopy

    <button class="btn btn-primary" @onclick="() => currentCount++">Click me</button>
    

    Event handler methods can optionally take an event argument with information about the event. For example, you can access the value of an input element that changed, like this:

    razorCopy

    <input @onchange="InputChanged" />
    <p>@message</p>
    
    @code {
        string message = "";
    
        void InputChanged(ChangeEventArgs e)
        {
            message = (string)e.Value;
        }
    }
    

    After an event handler runs, Blazor will automatically render the component with its new state, so the message is displayed after the input changes.

    https://lernix.com.my/g-add

  • Razor components

    Now that you have your development environment set up, let’s explore the structure of a Blazor project and learn how Blazor components work.

    The Home page

    The app’s home page is defined by the Home.razor file located inside the Components/Pages directory. Home.razor contains the following code:

    razorCopy

    @page "/"
    
    <PageTitle>Home</PageTitle>
    
    <h1>Hello, world!</h1>
    
    Welcome to your new app.
    

    The @page directive at the top specifies the route for this page, so that the Home component is displayed when the user navigates to the root of the app. The PageTitle tag is a Blazor component that sets the title for the current page so that it shows up in the browser tab. The rest of the file is normal HTML that defines the content for the page.

    What is Razor?

    Razor is a markup syntax based on HTML and C#. A Razor file (.razor) contains plain HTML and then C# to define any rendering logic, like for conditionals, control flow, and expression evaluation. Razor files are then compiled into C# classes that encapsulate the component’s rendering logic.

    What are Razor components?

    If you explore the files in the Blazor project, you notice that most of the files that make up the project are .razor files. In Blazor, a Razor file defines a reusable component that makes up a portion of the app UI. Components define what HTML to render and how to handle user events.

    At compile time, each Razor component is built into a C# class. The class can include common UI elements like state, rendering logic, lifecycle methods, and event handlers. Because Blazor components authored in Razor are just C# classes, you can use arbitrary .NET code from your components.

    Using components

    To use a component from another component, you add an HTML-style tag with a name that matches the component name. For example, if you have a component named MyButton.razor, you can add a MyButton component to another component by adding a <MyButton /> tag.

    Component parameters

    Components can also have parameters, which allow you to pass data to the component when it’s used. Component parameters are defined by adding a public C# property to the component that also has a [Parameter] attribute. You can then specify a value for a component parameter using an HTML-style attribute that matches the property name. The value of the parameter can be any C# expression.

    The @code block

    The @code block in a Razor file is used to add C# class members (fields, properties, and methods) to a component. You can use the @code to keep track of component state, add component parameters, implement component lifecycle events, and define event handlers.

    Try the Counter

    In the running app, navigate to the Counter page by selecting the Counter tab in the sidebar on the left. The following page should then be displayed:

    Screenshot of the Counter in the running app.

    Select the Click me button to increment the count without a page refresh. Incrementing a counter in a webpage normally requires writing JavaScript, but with Blazor, you can use C#.

    You can find the implementation of the Counter component at Components/Pages/Counter.razor.

    razorCopy

    @page "/counter"
    @rendermode InteractiveServer
    
    <PageTitle>Counter</PageTitle>
    
    <h1>Counter</h1>
    
    <p role="status">Current count: @currentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    
    @code {
        private int currentCount = 0;
    
        private void IncrementCount()
        {
            currentCount++;
        }
    }
    

    A request for /counter in the browser, as specified by the @page directive at the top, causes the Counter component to render its content. The @rendermode directive enables interactive server rendering for the component, so that it can handle user interface events from the browser.

    Each time you select the Click me button:

    • The onclick event is fired.
    • The IncrementCount method is called.
    • The currentCount is incremented.
    • The component is rendered to show the updated count.

    https://lernix.com.my/contact

  • Configure your development environment

    To get started with Blazor, you first need to install the .NET SDK and an appropriate code editor.

    Using the .NET SDK

    The .NET SDK includes templates for creating different kinds of .NET projects. You create a new project using the dotnet new <template-name> command. For example, to create a new Blazor web app project, you can run dotnet new blazor. Tools like Visual Studio and Visual Studio Code provide convenient user interfaces for creating .NET projects using the templates in the .NET SDK.

    Once you create a new .NET project, you can build and run the project using the dotnet build and dotnet run commands. You can use the dotnet watch command to build and run a project, then automatically apply code changes as they’re made. You can run and debug .NET projects from within Visual Studio and Visual Studio Code.

    Blazor tooling

    Blazor tooling is available with Visual Studio on Windows and with the C# Dev Kit extension for Visual Studio Code, which is supported on Windows, macOS, and Linux. Visual Studio on Windows is a fully integrated development environment (IDE), while Visual Studio Code is a lighter-weight code editor with a rich ecosystem of extensions. Both have free options available for learning and community use. When you install Visual Studio on Windows, it automatically includes the .NET SDK. The .NET SDK isn’t currently included with the C# Dev Kit for Visual Studio Code and must be installed separately.

    https://lernix.com.my/g-add-m

  • CRUD actions in ASP.NET Core

    Our pizza service supports CRUD operations for a list of pizzas. These operations are performed through HTTP verbs, which are mapped via ASP.NET Core attributes. As you saw, the HTTP GET verb is used to retrieve one or more items from a service. Such an action is annotated with the [HttpGet] attribute.

    The following table shows the mapping of the four operations that you’re implementing for the pizza service:

    HTTP action verbCRUD operationASP.NET Core attribute
    GETRead[HttpGet]
    POSTCreate[HttpPost]
    PUTUpdate[HttpPut]
    DELETEDelete[HttpDelete]

    You already saw how GET actions work. Let’s learn more about POSTPUT, and DELETE actions.

    POST

    To enable users to add a new item to the endpoint, you must implement the POST action by using the [HttpPost] attribute. When you pass the item (in this example, a pizza) into the method as a parameter, ASP.NET Core automatically converts any application/JSON sent to the endpoint into a populated .NET Pizza object.

    Here’s the method signature of the Create method that you’ll implement in the next section:

    C#Copy

    [HttpPost]
    public IActionResult Create(Pizza pizza)
    {            
        // This code will save the pizza and return a result
    }
    

    The [HttpPost] attribute maps HTTP POST requests sent to http://localhost:5000/pizza by using the Create() method. Instead of returning a list of pizzas, as we saw with the Get() method, this method returns an IActionResult response.

    IActionResult lets the client know if the request succeeded and provides the ID of the newly created pizza. IActionResult uses standard HTTP status codes, so it can easily integrate with clients regardless of the language or platform they’re running on.

    ASP.NET Core
    action result
    HTTP status codeDescription
    CreatedAtAction201The pizza was added to the in-memory cache.
    The pizza is included in the response body in the media type, as defined in the accept HTTP request header (JSON by default).
    BadRequest is implied400The request body’s pizza object is invalid.

    Fortunately, ControllerBase has utility methods that create the appropriate HTTP response codes and messages for you. You’ll see how those methods work in the next exercise.

    PUT

    Modifying or updating a pizza in our inventory is similar to the POST method that you implemented, but it uses the [HttpPut] attribute and takes in the id parameter in addition to the Pizza object that needs to be updated:

    C#Copy

    [HttpPut("{id}")]
    public IActionResult Update(int id, Pizza pizza)
    {
        // This code will update the pizza and return a result
    }
    

    Each ActionResult instance used in the preceding action is mapped to the corresponding HTTP status code in the following table:

    ASP.NET Core
    action result
    HTTP status codeDescription
    NoContent204The pizza was updated in the in-memory cache.
    BadRequest400The request body’s Id value doesn’t match the route’s id value.
    BadRequest is implied400The request body’s Pizza object is invalid.

    DELETE

    One of the easier actions to implement is the DELETE action, which takes in just the id parameter of the pizza to remove from the in-memory cache:

    C#Copy

    [HttpDelete("{id}")]
    public IActionResult Delete(int id)
    {
        // This code will delete the pizza and return a result
    }
    

    Each ActionResult instance used in the preceding action is mapped to the corresponding HTTP status code in the following table:

    ASP.NET Core
    action result
    HTTP status codeDescription
    NoContent204The pizza was deleted from the in-memory cache.
    NotFound404A pizza that matches the provided id parameter doesn’t exist in the in-memory cache.

    The exercise in the next unit demonstrates how to support each of the four actions in the web API.

    https://lernix.com.my/php-and-mysql-training-courses-malaysia

  • ASP.NET Core Web API Controllers

    In the previous exercise, you created a web application that provides sample weather forecast data, then interacted with it in the HTTP Read-Eval-Print Loop (REPL).

    Before you dive in to writing your own PizzaController class, let’s look at the code in the WeatherController sample to understand how it works. In this unit, you learn how WeatherController uses the ControllerBase base class and a few .NET attributes to build a functional web API in a few dozen lines of code. After you understand those concepts, you’re ready to write your own PizzaController class.

    Here’s the code for the entire WeatherController class. Don’t worry if it doesn’t make sense yet. Let’s go through it step by step.

    C#Copy

    using Microsoft.AspNetCore.Mvc;
    
    namespace ContosoPizza.Controllers;
    
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };
    
        private readonly ILogger<WeatherForecastController> _logger;
    
        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }
    
        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }

    https://lernix.com.my/red-hat-openstack-training-courses-malaysia

  • REST in ASP.NET Core

    When you browse to a webpage, the web server communicates with your browser by using HTML, CSS, and JavaScript. For example, If you interact with the page by submitting a sign-in form or selecting a buy button, the browser sends the information back to the web server.

    In a similar way, web servers can communicate with a broad range of clients (browsers, mobile devices, other web servers, and more) by using web services. API clients communicate with the server over HTTP, and the two exchange information by using a data format such as JSON or XML. APIs are often used in single-page applications (SPAs) that perform most of the user-interface logic in a web browser. Communication with the web server primarily happens through web APIs.

    REST: A common pattern for building APIs with HTTP

    Representational State Transfer (REST) is an architectural style for building web services. REST requests are made over HTTP. They use the same HTTP verbs that web browsers use to retrieve webpages and send data to servers. The verbs are:

    • GET: Retrieve data from the web service.
    • POST: Create a new item of data on the web service.
    • PUT: Update an item of data on the web service.
    • PATCH: Update an item of data on the web service by describing a set of instructions about how the item should be modified. The sample application in this module doesn’t use this verb.
    • DELETE: Delete an item of data on the web service.

    Web service APIs that adhere to REST are called RESTful APIs. They’re defined through:

    • A base URI.
    • HTTP methods, such as GETPOSTPUTPATCH, or DELETE.
    • A media type for the data, such as JavaScript Object Notation (JSON) or XML.

    An API often needs to provide services for a few different but related things. For example, our pizza API might manage pizzas, customers, and orders. We use routing to map URIs (uniform resource identifiers) to logical divisions in our code, so that requests to https://localhost:5000/pizza are routed to PizzaController and requests to https://localhost:5000/order are routed to OrderController.

    https://lernix.com.my/microsoft-system-center-certification-training-courses-malaysia