How to disable/override naming container's ID generation of Content page's control id's

浪子不回头ぞ 提交于 2020-01-02 03:15:30

问题


We have an existing ASP.Net web application which we want to convert into using masterpages. In the process of doing this, I found that the HTML id's generated for the HTML elements are prefixed with the ContentPlaceHolder's id. And this is what can be expected when we set the ContentPlaceHolder's clientidmode=static. Now since we have a lot of existing client side scripts that make use of the id's, this part breaks when we use masterpages, and it is quite a big job to run through all our javascript to make sure we call the javascript using Control.ClientID, as a lot of it is hardcoded.

Is there a way to disable the prefixing? I can succeed doing this, if I create every control setting its ClientIdMode=static, but then again I would prefer settings this once, to ensure that all controls are have their ClientIdMode=static. Is that possible? Or is it possible to override the NamingContainer of the ContentPlaceHolder?

The platform is .Net 4.0

(After fixing the above problem with ClientIdMode=static in the web.config as described in the answer below), I have bumped into the problem that the "name" attribute is automatically generated, and is not set to whatever it was before I introduced masterpages. This gives me a problem with my existing server code, which has many Request.Form[]. Any idea what best practice is here to solve this problem?

Thanks Jihad


回答1:


You can have ClientIDMode at Page Level:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ClientIDMode="Static" %>

MasterPage Level:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" ClientIDMode="Static" %>

and Web.Config level (making all pages inherit this behavior):

<system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <pages clientIDMode="Static"></pages>
</system.web>



回答2:


In case you don't target .Net framework 4, and the clientIDMode enum is not available, you can simply override the control class. Here is an example with HtmlGenericControl but can be done with any other control:

public class NoNamingContainerControl : HtmlGenericControl
{
    public NoNamingContainerControl(string tag) : base(tag) { }
    public override string ClientID
    {
        get
        {
            return this.ID;
        }
    }
}

This code should work on any .Net framework versions, although in .net 4 you should probably use the clientIDMode



来源:https://stackoverflow.com/questions/16114040/how-to-disable-override-naming-containers-id-generation-of-content-pages-contr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!