Alireza Hosseinitabar
Alireza Hosseinitabar

Reputation: 118

How to pass name attribute dynamically in ASP.NET Core Razor Pages partial tag helper?

I know I can reuse UI elements using <partial> tag helper.

For example, I can create a TextBox and reuse it this way:

<partial name="MyTextBox" model='new TextBoxModel { Label = "my lable" }' />

However, I need to be able to pass the name of the text box dynamically.

<partial name="FieldComponents.TextBoxComponent" />

I can't make it work. using @Html.Partial I could do it, and since <partial> tag is here to replace old HTML helpers, I expect it to support that.

How can I pass the name dynamically to <partial> tag in ASP.NET Core Razor Pages?

Upvotes: 0

Views: 1202

Answers (2)

Yiyi You
Yiyi You

Reputation: 18189

Here is a demo: Model:

public class FieldComponents
    {
        public string TextBoxComponent { get; set; }
    }

Index.cshtml.cs:

[BindProperty]
        public FieldComponents FieldComponents { get; set; } = new FieldComponents();
        public void OnGet()
        {
            FieldComponents.TextBoxComponent = "Partial1";
        }

Index.cshtml:

@page
@model RazorPageDemo.Pages.Test.IndexModel
<partial name="@Model.FieldComponents.TextBoxComponent" />

Partial1:

<h1>Partial1</h1>

result: enter image description here

Upvotes: 1

Mike Brind
Mike Brind

Reputation: 30075

You pass an expression that renders a string:

<partial name="@(DateTime.Now.Second %2 == 0 ? "_A" : "_B")"/>

Upvotes: 2

Related Questions