2013-07-03 52 views
2

我已经开始变量,并宣布他们为什么我的C#变量在Jquery中返回null?

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 
        } 
       } 
      }); 

我想通了,我放在<%=Image1%> javascript内部返回null,因为当我从href属性中删除所有值时,我得到了同样的错误。

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

最后,我测试,看看是否Request.QueryString返航空,因此我放置在标签

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

和路径张贴在标签图像的image1值。为什么jQuery中的变量为空?我错过了什么?

+1

您需要ReSharper - 它会警告您通过在Page_Load中定义一个新变量来隐藏受保护的Image1。 –

回答

9

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

行更改为这一点,它的工作:

Image1 = Request.QueryString["ImageAlt1"]; 
+1

在答案的第一分钟获得7张选票,现在8 ...猜猜影子向导是否在游戏中可能是代表系统? – tawman

+0

不,我提高了它,我不知道谁是暗影向导。 –

+0

游戏?他给出了第一个答案,它是一个很好的IMO,所以我赞成 – Jfabs

2

您有一个名为“图像1”的两个变量。其中一个(根据你写的代码)将永远不会被设置为任何东西(并且它是打印的)。

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"]; 
    } 
} 

通知缺乏string。通过在它的类型前加一个变量,你可以在那个范围内创建一个新的变量的本地实例。

+0

非常感谢sooo的解释。我应该知道这个我盯着它一个小时。我希望我能标记2作为答案暗影精灵击败你一拳,但你提供了一个很好的解释! – Skullomania