Skip to content

Razor Views

Jamie Pollock edited this page Feb 8, 2024 · 1 revision

General

By default models like IComponent, IElement and IModal use a convention system to render their content. This is somewhat of a replacement for Html.DisplayFor or Html.EditorFor.

Each of these types has a ViewName property which will be used in the view finding process when used with certain tag helpers.

The component is also wrapped in a generic ComponentMetaData<TModel> record. This provides additional context meta data to the view to aide with rendering. IElement and IModal have their own versions of MetaData too.

Basic Example

If we have a custom component like so:

public sealed record MyComponent(string Text) : IComponent
{
   // <inheritdoc/>
   public string ViewName => "MyComponent";
}

Using the default implementation, configuration and theme this will be located at /Views/Drop/Default/Components/MyComponent.cshtml.

Then the razor file would look like this:

@model ComponentMetaData<MyComponent>
<div class="my-component">
  <h1>@Model.Component.Text</h1>
</div>

Advanced Example

Carrying on from our basic example, let's say when we call <drop-component /> we add some HTML attributes.

<drop-component model="myComponent" class="standalone" data-target="custom" />

Now in our razor file for the component:

@model ComponentMetaData<MyComponent>
<div class="my-component" drop-attributes="Model.Attributes">
  <h1>@Model.Component.Text</h1>
</div>

This will add the attributes to the markup at runtime.

If your type has the IHaveAttributes (like IModal does) you can call an extension method Model.AllAttributes() instead which collates the object's models with any passed through to the tag helper.

Clone this wiki locally