Blog

  • 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>
    oracle certification malaysia

  • 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.

    Data binding

    Often you want the value of a UI element to be bound to a particular value in code. When the value of the UI element changes, the code value should change, and when the code value changes the UI element should display the new value. Blazor’s data binding support makes it easy to set up this sort of two-way data binding.

    You bind a UI element to a particular value in code using the @bind attribute. For example:

    razorCopy

    <input @bind="text" />
    <button @onclick="() => text = string.Empty">Clear</button>
    <p>@text</p>
    
    @code {
        string text = "";
    }
    

    When you change the value of the input, the text field is updated with the new value. And when you change the value of the text field by clicking the Clear button, the value of the input is also cleared.

    red hat certification malaysia
  • 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>
    veeam certification malaysia
  • 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.

    lpi linux administration certification 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();
        }
    }
    nodejs 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.

    vmware vsphere certification training courses malaysia

  • Hello world!

    Welcome to WordPress. This is your first post. Edit or delete it, then start writing!