如何在Jquery中正确调用C#变量.';变量名称';在当前上下文中不存在

本文关键字:变量名 不存在 上下文 变量 Jquery 调用 | 更新日期: 2023-09-27 18:20:43

我通过Request.QueryString在我的codeehind中存储了几个值,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        lblRow.Text = Request.QueryString["num"];
        string Image1 = Request.QueryString["ImageAlt1"];
        string Image2 = Request.QueryString["ImageAlt2"];
        string Image3 = Request.QueryString["ImageAlt3"];
    }
}

然后我尝试在jquery中调用这些值,得到一个does not exist in current context错误,这是我的jquery

$("#fancybox-manual-c").click(function () {
            $.fancybox.open([
    {
        href: "<%= Image1 %>",
        title: 'My title'
        }, {
        href: '<%= Image2 %>',
        title: '2nd title'
        }, {
        href: '<%= Image3 %>'
    }
            ], {
                helpers: {
                    thumbs: {
                        width: 75,
                        height: 50
                    }
                }
            });
        });

我不确定我做错了什么。我唯一的猜测是,jquery是在变量被提取之前被调用的,因为它应该被设置。

这是我的表单视图,我在其中调用我的其余项目:

<asp:FormView ID="FormView1" runat="server" DataSourceID="SqlDataSource3" 
    DataKeyNames="num">
     <ItemTemplate>
         <asp:Label ID="ItemType_Label" runat="server" Text='<%# Bind("ItemName") %>' />
         <br />
         <asp:Label ID="ItemDescription_Label" runat="server" Text='<%# Bind("ItemDescription") %>' />
         <br />
         <b>Asking Price:</b>
         <asp:Label ID="ItemPrice_Label" runat="server" Text='<%# Bind("ItemPrice") %>' />
         <br />
         <ul>
         <li><a id="fancybox-manual-c" href="javascript:;">Open gallery</a></li>
         </ul>
    </ItemTemplate>
</asp:FormView>

如何在Jquery中正确调用C#变量.';变量名称';在当前上下文中不存在

这一切都与范围有关。Image1Image2Image3Page_Load方法中的局部变量。您应该直接在类中声明它们,而不是在任何方法中声明。

public class MyApp
{
  public string Image1;
  public string Image2;
  public string Image3;
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
      lblRow.Text = Request.QueryString["num"];
      Image1 = Request.QueryString["ImageAlt1"];
      Image2 = Request.QueryString["ImageAlt2"];
      Image3 = Request.QueryString["ImageAlt3"];
    }
  }
}

今年早些时候我遇到了这个问题。试试这个Skullomana

public string Image1,Image2,Image3;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        lblRow.Text = Request.QueryString["num"];
        Image1 = Request.QueryString["ImageAlt1"];
        Image2 = Request.QueryString["ImageAlt2"];
        Image3 = Request.QueryString["ImageAlt3"];
    }
}

您需要在类级别定义这些变量,如

protected string Image1,Image2,Image3;
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        lblRow.Text = Request.QueryString["num"];
        Image1 = Request.QueryString["ImageAlt1"];
        Image2 = Request.QueryString["ImageAlt2"];
        Image3 = Request.QueryString["ImageAlt3"];
    }
}