Raghu's SharePoint Corner: QueryString Value using JavaScript in SharePoint

My blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://www.sharepointcolumn.com
and update your bookmarks.

August 28, 2010

QueryString Value using JavaScript in SharePoint

This post talks about how to use JavaScript to retrieve query string value from the URL and display it in an asp.net web control in an OOB SharePoint page. This might be a very common scenario in an ASP.Net environment, but when it comes to SharePoint the implementation is different and it may also take couple of hours to achieve this if you don’t have a complete idea about how SharePoint page works.

There are some limitations or rather you can say security related to SharePoint pages when it comes to JavaScript which access server side control. You cannot write directly access server side controls using JavaScript you need to make certain tweaks for this to work.

1.Make web.config changes so that you can access controls using JavaScript without getting “Page Parser Error message code blocks are not allowed”.

If you have scenario where you want to allow JavaScript in a particular page then you have to make the below entries in your pages

For ASPx Pages
<PageParserPaths> 

  <PageParserPath VirtualPath="/pages/[file name].aspx" CompilationMode="Always" AllowServerSideScript="true" /> 

</PageParserPaths>

For master page, this will enable inline code blocks for all master pages:

<PageParserPaths> 

  <PageParserPath VirtualPath="/_catalogs/masterpage/*" CompilationMode="Always" AllowServerSideScript="true" /> 

</PageParserPaths>

Making these changes will allow users who have access to Content DB to embed JavaScript in your site using SharePoint Designer.

2.The other option is to user HTML controls in your page. But even in this scenario SharePoint will adds an Auto Generated ID suffix and the control id changes like the one give below.

label id="lblName{generate-id}

So you may have to remove the auto generated suffix and keep only the label id.
So here goes the JavaScript which you can embed in a SharePoint page at the bottom and set the value of the control based on the query string

<script type="text/javascript">

var query = location.search.substring(1); 

if(query!=null)

{

 var query = location.search.substring(1).split('&');

 if(query .length>0)

 {

      var keys = query[0];

      var key = keys.split('=');

      var control=  document.getElementById('lblName');

      if(control!=null && key.length>0)

      {

        Control.innerText = key[1] ;

      }

 }

}

</script>

No comments: