Location>code7788 >text

NET8 Blazor from Start to Finish: (III) Class Libraries and Forms

Popularity:48 ℃/2024-08-19 17:34:08

catalogs
  • Razor Class Library
    • establish
    • utilization
      • Making routable components available from the RCL
    • Static resources
  • form (document)
    • EditForm
      • Standard Input Components
      • validate (a theory)
    • HTML Forms

Razor Class Library

Here is only a brief overview of the creation and use of RCL, refer to the official documentation for details.Using Core Razor Components from the Razor Class Library (RCL)

establish

Creating a Razor library is the same as creating a normal library, the key steps are as follows:

  • From CoreSelect "Razor Class Library" from the list of project templates.
  • In the Other Information dialog box.Do not select "Support pages and views".

utilization

Using components from RCL in your project is the same as using regular libraries:

  • Use the full component type name that contains the RCL namespace
  • If Razor's@using commandWhen an RCL namespace is declared, individual components can be added with names that do not contain an RCL namespace. Use the following method:
    • Adding the @using directive to components
    • Add @using directive to _Imports.razor file
      • Include the @using directive in the top-level _Imports.razor file to make the library's components available to the entire project.
      • Add a directive to the _Imports.razor file at any level to apply the namespace to a single component or group of components in a folder.

Making routable components available from the RCL

To make the routable components of the RCL available for direct requests, you must expose the RCL's assemblies to the application's routers. Open the server project's file and add the following code:

<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(._Imports).Assembly)
    //Add the following code,pull intoRCLassembly
    .AddAdditionalAssemblies(typeof(RazorClassLibrary1._Imports).Assembly);

Static resources

RCL's static assets can be used in any application that uses the library.Place static assets in the wwwroot folder of the RCL, and reference static assets in your application using the following path:

_content/{PACKAGE ID}/{PATH AND FILE NAME}
  • {PACKAGE ID}: the package ID of the library, or the package ID of the library if not specified.The package ID defaults to the assembly name of the project
  • {PATH AND FILE NAME} : Path and filename under wwwroot

This path format is also used in applications for static assets provided by NuGet packages added to the RCL.

form (document)

The component renders standard HTML elements and can actually use standard HTML form elements. However, it is recommended to use the various Blazor input controls as they come with additional functionality. For more details about the component, please refer to the official documentation Core Blazor Forms Overview

EditForm

Blazor provides a standard set of available input components, all derived from the base classInputBase<T> :
image

Standard Input Components

The following is an example of the use of the standard input components, which are relatively simple and will not be introduced separately:

@page "/demo"
@rendermode InteractiveAuto

<h3>Demo</h3>
<EditForm Model="FormData">
    <label>Input checkboxes Boolean:</label>
    <InputCheckbox @bind-Value= /> <br />

    <label>Enter date DateTime:</label>
    <InputDate @bind-Value= ParsingErrorMessage="Must be a date" /> <br />

    <label>input number:</label>
    <label>Input integer Integer:</label><br />
    <InputNumber @bind-Value= ParsingErrorMessage="Must be an integer value" /> <br />
    <label>Input Decimal Decimal:</label> <br />
    <InputNumber @bind-Value= ParsingErrorMessage="Must be a decimal value" /> <br />

    <label>Input Selection Select:</label>
    <InputSelect @bind-Value=>
        @foreach (var item in (typeof(State)))
        {
            <option value=@item>@()</option>
        }
    </InputSelect><br />

    <label>input radio button Radio:</label> <br />
    <InputRadioGroup @bind-Value=>
        @foreach (var item in (typeof(State)))
        {
            <InputRadio Value=@item />
            @()
            <br />
        }
    </InputRadioGroup>

    <label>input text String:</label> <br />
    <InputText @bind-Value= /> <br />

    <label>Entering multiple lines of text String:</label> <br />
    <InputTextArea @bind-Value= /> <br />
</EditForm>
@code
{
    //Indicates that the value of the associated attribute should be provided from the form data
    [SupplyParameterFromForm]
    private TestModel FormData { get; set; } = new TestModel();

    class TestModel
    {
        public bool Boolean { get; set; }
        public DateTime? DateTime { get; set; }
        public int Integer { get; set; }
        public decimal Decimal { get; set; }
        public string String { get; set; }
        public string MultiLineStr { get; set; }
        public State Select { get; set; } = ;
        public State Radio { get; set; }= ;
    }

    public enum State
    {
        Pending,
        Active,
        Suspended
    }
}

The running effect is as follows:
image

validate (a theory)

Form validation requires two things:

  • must be added inside the EditForm with aValidation Component DataAnnotationsValidatorEditForm
  • This can be done in two ways to the userShow validation error messageThe two are not conflicting and can be used at the same time:
    • ValidationSummary: show a complete list of all errors in the form
    • ValidationMessage: Display an error message for a specific input
      Here is a simple example, note the use of theOnValidSubmitevent, otherwise the validation will not take effect:
@page "/demo"
@rendermode InteractiveAuto
@using

<h3>Demo</h3>
<EditForm Model=@Person FormName="personForm" OnValidSubmit=@SubmitForm>
    @* Must specify a validation mechanism *@
    <DataAnnotationsValidator />
    @* Display a complete list of all errors in the form *@
    <ValidationSummary />

    <div class="form-group">
        <label for="Name">Name</label>
        <InputText @bind-Value=/>
        @* Display error message for a single field *@
        <ValidationMessage For="() => " />
    </div>

    <div class="form-group">
        <label for="Age">Age</label>
        <InputNumber @bind-Value=/>
        @* Referencing "" and Razor expressions @(...) Both forms are equivalent
        1. The quoted form is easier to read.
         Expressions make it clear that the definition is an expression and not a string *@
        <ValidationMessage For=@(() => ) />
    </div>
    <input type="submit" class="btn btn-primary" value="Save" />
</EditForm>
@code {
    // Validation requires the introduction of a namespace
    public class PersonModel
    {
        // Specify that the attribute cannot be null or empty.
        [Required(ErrorMessage = "Name cannot be null.")]
        public string Name { get; set; }

        // Specify a range of valid values for the attribute (from 18 to 80) and also provide an error message suitable for displaying to the user.
        [Range(18, 80, ErrorMessage = "Age must be between 18 and 80.")]
        public int Age { get; set; }
    }

    [SupplyParameterFromForm]
    private PersonModel Person { get; set; } = new PersonModel();
}

The running effect is as follows:
image

HTML Forms

Using regular HTML<form> tag creates the form and specifies the@onsubmit Handling procedures:

@* Table name must be provided *@
<form @formname="htmlForm" @onsubmit="SubmitForm">
    @* For safety's sake.,must provide AntiforgeryToken *@
    <AntiforgeryToken />
    <div class="form-group">
        <label for="Name">Name</label>
        <InputText @bind-Value= class="form-control" />
    </div>
    <div class="form-group">
        <label for="Age">Age</label>
        <InputNumber @bind-Value= class="form-control" />
    </div>
    <input type="submit" class="btn btn-primary" value="save (a file etc) (computing)" />
</form>

Include theAntiforgeryToken Component to include anti-counterfeiting support, see official documentation for detailsAnti-counterfeiting support

For EditForm-based forms, the default is to automatically add theAntiforgeryToken assemblies and[RequireAntiforgeryToken] attributes to provide protection against counterfeiting.