Link to home
Start Free TrialLog in
Avatar of elmoredaniel
elmoredaniel

asked on

Check if URL variable exists

I've never written a line of C#, so don't laugh at me here. All I need to do is check to see if a URL variable exists, if so I need to output a few lines of javascript. How shall I do so?

Thank you
Avatar of orbulat
orbulat
Flag of Hong Kong image

1. drag a hidden variable in design mode, eg. <input type=hidden id=hidURL runat=server />
2. in your code behind add this function for checking url, this function may run a little bit slow

public bool checkURL(string url)
{
   try
   {
      HttpWebRequest hReq= (HttpWebRequest)WebRequest.Create(url);
      HttpWebResponse hResp = (HttpWebResponse)hReq.GetResponse();
      hResp .Close();
      return true;
    }
    catch
    {
       return false;
    }
}

3. in Page_Load

add the following:

if (!checkURL("http://www.your_url.com"))
{
     hidURL.value = "false";
}

4. in your javascript:

if (document.Form1.hidURL.value == "false")
   alert("url is invalid!");
Avatar of elmoredaniel
elmoredaniel

ASKER

Humm, don't know if that's what I needed, maybe I'm wrong.

I have a javascript tag and if the page is accessed with "admin" in the query string ie. (page.aspx?admin)  Then I need to output:  a javascript alert.

So can't C# do something like:

<script language="javascript">

if(url_variable_admin_exists ...)
   alert('the variables exists');

</script>
Hi,
You can get the url with the help of Request.
For instance, say

String URL = Request.Path.ToLower();

now you have the complete url with you.
URL has got different segments. You can get all the parts using Segments and use it as per your requirement

do let me know if you have further doubts so that i can help you on this
HTH

Happy Programming
Rana

So you want to check what is in the URL?

Does it really look like page.aspx?admin or can you make it look something like page.aspx?usertype=admin

If you can make it look this my second option then in your codebehind do this

string userType = Request.QueryString["usertype"]
if( userType == "admin")
{
      this.RegisterStartupscript("alert","<script language='javascript'>alert('the variable is admin');</script>");
}

Use "Request.Url.Segments" to fetch different parts of the URL
Rana
Apparently no one read my question, because it says "I've never written a line of C#"   and I will never have to again after this.

GavinMannion your code looks the most promising. But I don't know what a codebehind is. Can't I place this code directly in the page. Also, it looks like your code requires the url variable "usertype" to exists, which it may not exist.

Thank you
ASKER CERTIFIED SOLUTION
Avatar of GavinMannion
GavinMannion

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial