为什么我的C#变量在Jquery中返回null?

为什么我的C#变量在Jquery中返回null?,c#,jquery,C#,Jquery,我已经启动了变量并声明了它们 protected string Image1; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string Image1 = Request.QueryString["ImageAlt1"]; } } 我已经正确地调用了jquery中的变量,当我测试链接时,什么都没有得到 $("#fancybox-manual

我已经启动了变量并声明了它们

protected string Image1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        string Image1 = Request.QueryString["ImageAlt1"];
    }
}
我已经正确地调用了jquery中的变量,当我测试链接时,什么都没有得到

 $("#fancybox-manual-c").click(function () {
            $.fancybox.open([
                {
                    href: '<%=Image1%>',/*returns '' instead of 'path/image.jpg'*/
                    title: 'My title'
                }
            ], {
                helpers: {
                    thumbs: {
                        width: 75,
                        height: 50
                    }
                }
            });
最后,我测试了
Request.QueryString
是否返回null,因此我将
image1
的值放在标签中

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

以及标签中发布的图像的路径。为什么jQuery中的同一变量为空?我遗漏了什么?

因为您将值设置为仅在if条件范围内创建的局部变量

将行更改为该行,它将工作:

Image1 = Request.QueryString["ImageAlt1"];

您有两个名为“Image1”的变量。其中一个(根据您编写的代码)永远不会被设置为任何值(并且是打印的)

试试这个

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

注意缺少
字符串
。通过按类型预先设置变量,您可以在该范围内创建该变量的新本地实例。

您需要重新精简-它会警告您,您已通过在Page_Load中定义新变量来隐藏受保护的图像1。在回答的第一分钟内获得7票,现在是8票。。。猜影子巫师可能在玩rep系统?游戏?他给出了第一个答案,在我看来这是一个很好的答案,所以我想也许我需要经常来这里。。。在前60秒内从未见过像这样实时投票的问题。。。继续。我认识乔恩·斯基特,他不是影子巫师;)相当有趣的社会动态,我偶然发现。。。稍后非常感谢你的解释。我早该知道我盯着它看了一个小时。我希望我能在回答时打2分,因为阴影巫师打败了你,但你提供了一个很好的解释!
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)
}
protected string Image1;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        Image1 = Request.QueryString["ImageAlt1"];
    }
}