Nov
9
2008

Cross page request variables in ASP.NET



Comments available as RSS 2.0

If you have a page which uses a master page, then put controls inside a ContentPlaceHolder on the sub page, accessing the values of the controls can be difficult if you’re posting the form to another page. The problem is, the ContentPlaceHolder mangles the control names so instead of radApplication, you get ctl00$cntMain$radApplication, meaning you can’t read them from Request.Form.

Hardcoding the name of the placeholder would be a bad idea incase you ever change the name of it or change the master page. There are actually two ways you can get at the controls.

The first way, which works if you just need access to the value posted involves looping through Request.Form.AllKeys to find the name of the control.

string appName = string.Empty;
foreach(string key in Request.Form.AllKeys) {
  if(key.endsWith("radApplication")) {
    appName = Request.Form[key];
  }
}

While this works, it could break if there were several controls with similar names on the page. The second method uses the PreviousPage property to provide a reference to the actual control.

ContentPlaceHolder previous = (ContentPlaceHolder)PreviousPage.Master.FindControl("cntMain");
string projectID = (previous.FindControl("radApplication") as RadioButtonList).SelectedValue;

The benefit of getting a reference to the actual control is that you can see more than just the value submitted on the form.

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Comments

Leave a Comment

Login using OpenID or enter your details below to leave a comment.

OpenID
Anonymous


Comment

Powered by WP Hashcash