c# - 如何在 Jquery 中正确调用 C# 变量。 'variable name'当前上下文中不存在

标签 c# jquery sql webforms

我在代码隐藏中将几个值存储为via Request.QueryString,如下所示:

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 中调用这些值,但出现 当前上下文中不存在 错误,这是我的 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 在变量被选取之前被调用,因为它应该被设置。

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

<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>

最佳答案

一切都与范围有关。 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"];
    }
  }
}

关于c# - 如何在 Jquery 中正确调用 C# 变量。 'variable name'当前上下文中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17435049/

相关文章:

c# - C# 中的 SqlConnection - 安全编程实践

jquery - 如何将字典发送回 Django View ?

jQuery 和 Grails/HTML - 使文本字段像 Google 一样完成文本

sql - SQL 中的自引用 CASE WHEN 子句

mysql - 多次查询数据库的最有效方法

c# - 无返回值的条件运算符

c# - VSCode调试测试。错误 MSB1011 : Specify which project or solution file to use because this folder contains more than one project or solution file

c# - 如何在 XML 文档中包含 DTD

javascript - 当我按退格键时仍然显示错误消息(e.which ==8)

sql - 如何获取星期六的日期(或任何其他工作日的日期)- SQL Server