Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 482
Jihad Haddad Avatar asked Apr 19 '13 21:04

Jihad Haddad


2 Answers

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>
like image 55
Hanlet Escaño Avatar answered Nov 02 '22 01:11

Hanlet Escaño


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

like image 27
Shai Petel Avatar answered Nov 02 '22 02:11

Shai Petel