0

I like to create a ASP.NET MVC Application, where the pages are rendered on the server side. After reading a lot of documentation I couldn't find a way to achieve a modular way of creating components.

I found a way to create Custom Tag Helpers and a way to create Razor Components. But somehow I can't use a Razor Component in a Razor Component.

So what I basically want to do is to write some Razor components, which I can reuse in other Razor Components and so build my app modular.

For better understanding a simple example:

I want to write a component like a Button. Then I want to create a second component, called Icon.

For example: index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

<Button text="Click me" link="/" iconclass="fa-solid fa-pen-to-square"></Button>

The Button component should look something like: Button.razor

<a class="btn btn-primary" href="@link">Click me <Icon iconclass="@iconclass"></Icon></a>

And the icon component like: Icon.razor

<i class="@iconclass"></i>

This should render the following HTML Code:

<a class="btn btn-primary" href="/">Click me <i class="fa-solid fa-pen-to-square"></i></a>

I achieved it, to include one component in index.cshtml

@{
    ViewData["Title"] = "Home Page";
}

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

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div> 

but when I do the same in the razor Component, it does not work.

<a class="btn btn-primary">
    Click me
    <component type="typeof(Icon)" render-mode="ServerPrerendered" />
</a>

Is there a way to achieve such a modular structure in ASP.Net?

11
  • Are you talking about Html helper? Commented Aug 25, 2022 at 15:19
  • If there is a way to create a custom HTML Helper, which I can reuse in different Razor components, that would be a feasible solution. Commented Aug 25, 2022 at 15:24
  • Of course u can create ur own html helper Commented Aug 25, 2022 at 15:26
  • Thank you very much for your answer. I really appreciate your help. How do I use a html helper in a rezor component? Commented Aug 25, 2022 at 15:32
  • are you using MVC5 or Core? Commented Aug 25, 2022 at 15:40

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.