how to use components in razor pages?

mc 3,701 Reputation points
2023-01-19T02:14:12.6466667+00:00

I know I can use component like this:

<component type="typeof(Editor)" render-mode="ServerPrerendered" />

but can I use it like

<Editor />

or

<my-editor />

with out import blazor?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,199 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,281 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tiny Wang-MSFT 1,571 Reputation points Microsoft Vendor
    2023-01-19T08:06:34.54+00:00

    I trust you already knew that <component> is a build-in Tag helper in asp.net core for blazor. And if you want to use html tag like <Editor /> or <my-editor />, we need to custom the tag helper.

    I have an example for a custom select tag helper, below is the taghelper class.

    using Microsoft.AspNetCore.Razor.TagHelpers;
    using System.Net;
    using System.Text;
    
    namespace WebAppMvc.Models
    {
        public class MselectTagHelper : TagHelper
        {
           public List<MySelectListItem> list { get; set; }
           public string aspFor { get; set; }
    
           public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                output.TagName = "select";
                output.Attributes.SetAttribute("id", aspFor);
                output.Attributes.SetAttribute("name", aspFor);
                var options = "";
                if (list != null) {
                    foreach (var item in list)
                    {
                        options += $@"<option value={item.Value} data-image-url={item.data_image_url}>{item.Text}</option>";
                    }
                    output.Content.SetHtmlContent(options);
                }
            }
        }
    }
    

    And when I want to use it in the view, it looks like:

    <Mselect asp-for="Country" list="Model.Countries"></Mselect>
    

    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best Regards,

    TinyWang

    0 comments No comments

0 additional answers

Sort by: Most helpful