Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the ASP.NET Core equivalent of ViewData.TemplateInfo.GetFullHtmlFieldId("PropertyName")?

I'm migrating a web app to .NET Core, and it uses a few Razor editor templates for specific input types (e.g. outputting a date input for any DateTime model properties).

A couple of the templates use the following method to get the ID attribute value, for use elsewhere within the HTML:

ViewData.TemplateInfo.GetFullHtmlFieldId("PropertyName")

However, this method no longer seems to exist in ASP.NET Core.

The GetFullHtmlFieldName method still exists, so it's possible to get the same result (at least for everything I've tested) by doing:

Regex.Replace(ViewData.TemplateInfo.GetFullHtmlFieldName("PropertyName"), @"[\.\[\]]", "_")

But this seems a little untidy to me, not to mention that there could be edge cases which the old method deals with that I don't know about.

Half an hour of googling, reading the .NET Core docs and searching SO hasn't turned up anything useful. The only thing I could find which was remotely relevant was this answer (which just confirms the method is gone).

Does anyone know why GetFullHtmlFieldId no longer exists? Is it just an accidental omission, or is there a newer, better way of getting this now?

like image 741
Mark Bell Avatar asked Jun 07 '19 06:06

Mark Bell


1 Answers

I had a look through the ASP.NET Core repository, and it looks like TemplateInfo.GetFullHtmlFieldId() was originally removed due to a static reference to HtmlHelper.

After a lot of digging around (the .NET Core source browser is an amazingly useful tool), I think the solution for my problem is to use IHtmlHelper.GenerateIdFromName. So, this code:

ViewData.TemplateInfo.GetFullHtmlFieldId("PropertyName")

should now be written as:

Html.GenerateIdFromName(ViewData.TemplateInfo.GetFullHtmlFieldName("PropertyName"))

Still not all that tidy (or consistent), but at least this way we're re-using the same internal logic that the framework uses to construct its IDs.

like image 123
Mark Bell Avatar answered Sep 20 '22 14:09

Mark Bell