Search code examples
c#asp.nethttpwebrequestmaster-pages

Master Page is adding additional text in TextBox ID


I have a master page which has a content section with the id cpMainContent. I am using this master page on every webform I am creating for college project. One of such form is frmSearchPersonnel. The purpose of frmSearchPersonnel is to ask user last name of the person they want to search in a textbox and then click on search button. The ID of TextBox is

        txtSearchName

Search button will do postbackUrl transfer to another form which I have named frmViewPersonnel. In frmViewPersonnel I am trying to use following code.

        NameValueCollection myRequest = Request.Form;
        if(!string.IsEmptyOrNull(myRequest["txtSearchName"]))
           string strSearch = myRequest["txtSearchName"];

The problem I ran into is that this didn't find any control with the name of txtSearchName. While debugging I found this in myRequest object,

                [5] "ctl00$cpMainContent$txtSearchName" string

Even though when I added textbox I gave it ID of txtSearchName but when page is rendered it is adding extra string from master page.

  1. How can I stop this? I have to use master page so don't say not to use master page :)
  2. Why is it doing that?

Update

While Googling and Binging I found that I can use Control.ClientID in this case so looking into it.

Update 2

As suggested below to add ClientIDMode="static" in the html of control or add it in page directive. What it does is, it keeps the ID static to txtSearchName but problem is this,

         <input name="ctl00$cpMainContent$txtSearchName" type="text" id="txtSearchName" />

Here name is still using ctl00 and the code I showed above,

            string strSearch = myRequest["txtSearchName"] 

it still won't work because nvc collection is either searchable by index or name not the id directly.

============== enter image description here


Solution

  • If you are posting to another page that uses the same master page (called SiteMaster in my case), the name of the textbox should be same the same.

    string val = Request[((SiteMaster)Master).txtSearchName.UniqueID];
    

    If you're NOT posting to a page with the same master, well, then are you using the viewstate for the textbox at all since you're posting to another page? If not, just make the control a non asp.net control:

    <input type="text" name="txtSearchName"/>
    

    If you are using viewstate and posting to another page with a different master page, well, you should use PreviousPage.