Getting Razor component id

It seems odd there is no standard way of getting the name of a control rendered with the Html helper extensions in MVC3 Razor. I saw some proposed solutions, but none of the actually worked e.g. in partial views or list binding.

This solution gets it right, but is nonetheless just another hack. You can easily modify the regular expression to get the id instead of the name.

@using System.Text.RegularExpressions  
@{var regex = new Regex(  
      @"\sname\=""(?'val'[^""]+?)""",
      RegexOptions.CultureInvariant | RegexOptions.Compiled | RegexOptions.ExplicitCapture); }
:
@Html.TextBoxFor(m => m.Value)          
<span data-valmsg-for="@(regex.Match(Html.TextBoxFor(m => m.Value).ToHtmlString())
                              .Groups[1]
                              .Value)"></span>
Google
m@kli.dk @klinkby RSS feed  GitHub