Remove default ID attribute from HTML helpers in ASP.NET MVC
By default, MVC's input html helpers generate "id" and "name" with the same value. In my case i do not need the id, and when i do, I always en开发者_如何学运维ter a custom value. Auto generating unnecessary id's increases the document size, and makes me nerves, because i might be using the same id in my CSS or JavaScript code.
Can i alter the default behavior of the html helpers, so the id is not generated unless manually defined.
I know that i can tell the helpers not to generate an id by passing new { id = "" }
, but this approach is not very convenient for large, data-entry-type applications.
Is there an easy way to alter this behavior, or do i need to write custom html helpers?
use,
Html.TextBoxFor(m => m.Text).RemoveNameIdAttribute()
public static MvcHtmlString RemoveNameIdAttribute(this MvcHtmlString helper)
{
if (helper == null)
throw new ArgumentNullException();
var element = helper.ToString();
var regex = new Regex("(id|name)[^'\"]*['\"][^'\"]*['\"]",RegexOptions.IgnoreCase | RegexOptions.Compiled);
return MvcHtmlString.Create(regex.Replace(element, ""));
}
I don't believe you can override the default behavior of the HTML Helpers... but can give some bits of advice.
I'm not worried about extra "id" normally, as proper CSS structure and convention can help to prevent that. Where there can be conflict, send in a new { id = "foo", name = "foo" }
.
I seriously doubt that the "id = myfield" characters are going to add up to much. If you're interested in compression, you could take a look at Combres: (http://combres.codeplex.com/).
Outside of this, the solution may be to create your own HTML helpers, which can override the basic ones, passing in your new { id = "" }
(Haven't tested that.)
Hope that helps.
精彩评论