Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my C# variable return null in Jquery?

Tags:

jquery

c#

I have initiated the variables and declared them

protected string Image1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string Image1 = Request.QueryString["ImageAlt1"];
    }
}

I have called the variables from jquery properly and when I test the link I get nothing

 $("#fancybox-manual-c").click(function () {
            $.fancybox.open([
                {
                    href: '<%=Image1%>',/*returns '' instead of 'path/image.jpg'*/
                    title: 'My title'
                }
            ], {
                helpers: {
                    thumbs: {
                        width: 75,
                        height: 50
                    }
                }
            });

I figured out that the <%=Image1%> that I placed inside the javascript was returning null because when I removed all values from the href attribute I got the same error.

href:'' /*causes the jquery not to fire when the link is clicked*/

Finally, I tested to see if the Request.QueryString was returning null so I placed the value of image1 in a label

lblImage1.Text = Image1; //returns 'path/image.jpg'

And the path to the image posted in the label. Why is the same variable blank in jQuery? What am I missing?

like image 485
Skullomania Avatar asked Apr 15 '26 08:04

Skullomania


2 Answers

Because you set value to local variable created in the scope of the if condition only.

Change the line to this and it will work:

Image1 = Request.QueryString["ImageAlt1"];

You have two variables named "Image1". One of them will (according to the code you wrote) never be set to anything (and it's the one that's printed).

protected string Image1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string Image1 = Request.QueryString["ImageAlt1"]; // introduces a new variable named Image1
        // this.Image1 and Image1 are not the same variables
    }
    // local instance of Image1 is no more. (out of scope)
}

Try this instead

protected string Image1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Image1 = Request.QueryString["ImageAlt1"];
    }
}

Notice the lack of string. By prepending a variable by it's type, you create a new local instance of that variable there, in that scope.

like image 34
Alxandr Avatar answered Apr 17 '26 23:04

Alxandr