Search code examples
c#asp.net-corerazor-pagesasp.net-core-tag-helpersasp.net-core-7.0

Replicate asp-for functionality on any element


ASP.NET Core's <input> and <label> tag helpers support the asp-for property, which generates id, name and for appropriately.

Is it possible to get those values somehow and use them on some other element?

For example, this:

<input [email protected] />
<div [email protected]=>Foo</div>

Renders this:

<input id="User_Name" name="User.Name" ... />
<div [email protected]>Foo</div>

Obviously the asp-for won't work on the div, but I'd like to do something like that. Is that possible?

(Currently I either hardcode the values or use some kludge involving multiple nameof calls. I prefer a dynamic solution that works similarly to asp-for.)


Solution

  • Thanks to the comment by @browsermator, this is possible using IHtmlHelper<TModel>.

    Those were an important part of ASP.NET almost ten years ago - i.e. before ASP.NET Core - so I forgot about them completely. They are still available.

    Suppose I have an input, and want to reference it (via JavaScript) from some related element:

    <input [email protected] ... />
    <div for="@(Html.IdFor(x => x.User.Name))">Foo</div>
    

    That renders:

    <input id="User_Name" name="User.Name" ... />
    <div for="User_Name">Foo</div>
    

    One could also use Html.NameFor or whatever else is appropriate.