Getting query string value using Javascript in MVC


Introduction

This article contains code snippet for getting querystring value using javascript

Code Snippet

This javascript function retrieves query string value from url taking querystring name as parameter

 <script>  
 function getParameterByName(name) {  
 url = window.location.href;  
 name = name.replace(/[\[\]]/g, "\\$&");  
 var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),  
 results = regex.exec(url);  
 if (!results) return null;  
 if (!results[2]) return '';  
 return decodeURIComponent(results[2].replace(/\+/g, " "));  
 }  
 </script>  

Calling above function

This below javascript code calls above declared function for displya querystring value

 <script>  
 var vl=getParameterByName('id');  
 if(vl){  
 alert(vl)       
 }  
 </script>  



Summary

Hope this code snippet may help you to resolve your problem.

Thanks