使用C#Page.aspx中的参数调用Javascript函数

Call Javascript function with parameters from C# Page .aspx

本文关键字:调用 Javascript 函数 参数 C#Page aspx 使用      更新时间:2023-09-26

我有RegisterClientScriptBlock,它写在.aspx文件protected void Page_Load(object sender, EventArgs e) 的页面加载中

脚本实际上从URL获取ID,然后将其传递给javascript的openticketPageLoad()函数。

但它没有进入openticketPageLoad()函数。但是.aspx页面正在加载

openTickets.aspx.cs

public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "openTicketsScript", "<script type=''type/javascript''>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);
}
}

在我的javascript文件中

function openticketPageLoad(b)
{
alert(b); //No alert window coming.
}

请参阅此处的文档:http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerclientscriptblock.aspx

最后一个参数是一个布尔值,用于指定ASP.net是否应生成Script标记。正如您已经指定的那样,我希望如果您查看源代码,您将生成嵌套的脚本标记。

您可以尝试以下代码吗:

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(this.GetType(), 
                "openTicketsScript", string.Format("openticketPageLoad({0});", Request.QueryString["ID"]), true);
    }
}

试试这个

Page.ClientScript.RegisterStartupScript(this.GetType(), "openTicketsScript", "<script type=''type/javascript''>$(document).ready(function(){openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");});</script>".ToString(), true);

也许您可以在页面主体的加载事件中直接将调用分配给javascript函数。要从内容页面分配正文的加载功能,可以执行以下操作:

HtmlGenericControl body = this.Master.FindControl("body") as HtmlGenericControl;
                body.Attributes.Add("onLoad", "openticketPageLoad(" + Request.QueryString["ID"].ToString() + ");");

在主页面中,将runat="server"添加到body元素:

<body id="body" runat="server">

我希望这能有所帮助。