在ASP.NET MVC HTML辅助删除默认的ID属性 [英] Remove default ID attribute from HTML helpers in ASP.NET MVC
问题描述
在默认情况下,MVC的输入HTML辅助生成id和名称具有相同的价值。在我来说,我不需要ID,当我做什么,我总是输入自定义值。自动生成不必要的id会增加文件大小,让我的神经,因为我可能会使用相同的ID在我的CSS或JavaScript code。
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 enter 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.
我可以改变HTML辅助的默认行为,所以除非手动定义不生成的ID。
Can i alter the default behavior of the html helpers, so the id is not generated unless manually defined.
我知道,我可以告诉助手不通过传递新{ID =}
,但这种方法并不适合大很方便,数据生成一个id -entry类型的应用。
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.
有没有一种简单的方法来改变这种行为,或者我需要编写自定义HTML佣工?
Is there an easy way to alter this behavior, or do i need to write custom html helpers?
推荐答案
使用,
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, ""));
}
这篇关于在ASP.NET MVC HTML辅助删除默认的ID属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!