1

I'm using MVC3 with Razor and I've noticed that Html helper functions generate html tags that have their names attributes like I asked them to, but have specific format for id attribute. If I try to generate a checkbox and pass "item[0]" as a name parameter, I'll get a checkbox with "item[0]" as name but "item_0_" for id.

I'm guessing there's a good reason for that, and I'm guessing that there's a function that does this string to string conversion? Do you know which function does that? I need to do this type of conversion in my code.

tereško
  • 58,060
  • 25
  • 98
  • 150
durad
  • 315
  • 1
  • 5
  • 9

4 Answers4

2

I think you are looking for:

GetFullHtmlFieldId

http://msdn.microsoft.com/en-us/library/system.web.mvc.templateinfo.getfullhtmlfieldid.aspx

B Z
  • 9,363
  • 16
  • 67
  • 91
0

This probably happens because a [ is not valid in an html id. Such a funciton would be very easy to write yourself though:

public string SanitizeID(string dirtyID)
{
     return dirtyID
         .Replace("[", "_")
         .Replace("]", "_")
         .Replace(".", "_");

     // add any other replace as needed
}

EDIT
This answer might point you in the right direction: Preventing ASP.NET MVC from Replacing period with underscore in Html Helper IDs

EDIT 2
This post of Scott Hanselman appears to hint that such behaviour is defined in the DefaultModelBinder.cs class. I cannot check the ASP.NET MVC sources now, but you might want to take a look there...

Community
  • 1
  • 1
Sergi Papaseit
  • 15,999
  • 16
  • 67
  • 101
  • That's what I did, but I's rather use the system function, since I'm not sure which other replacements I need to do. – durad Mar 24 '11 at 14:01
  • @77v - I've added a link to an answer that might get you closer to what you want... although not completely there, I'll admit... – Sergi Papaseit Mar 24 '11 at 14:27
0

This may be in the Control class in asp.net - have a look there, not MVC

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
0

Taken from the MSDN page for Control.ID Property:

Note
Only combinations of alphanumeric characters and the underscore character ( _ ) are valid values for this property. Including spaces or other invalid characters will cause an ASP.NET page parser error.

So it looks like you should be ok using something like:

string id = ...;
id = Regex.Replace(id, @"\W", "_");

But yes it would be nice to find a system method.

Buh Buh
  • 7,443
  • 1
  • 34
  • 61