从asp.net正确执行javascript代码

Executing the javascript code properly from asp.net

本文关键字:执行 javascript 代码 asp net      更新时间:2023-09-26

我试图从TestConfirmValue()方法在后面的代码,但当javascript函数callCheckMethod()被调用,函数的最后一行

alert("<%= TestConfirmValue() %>")在其他操作之前被调用。首先调用TestConfirmValue(), confirm_value总是空的。

在调用TestConfirmValue()之前,我如何才能从javascript函数中首先设置confirm_value ?

On Code behind:

      protected override void OnPreRender(EventArgs e)
{
        ClientScript.RegisterStartupScript(GetType(), "Javascript", "callCheckMethod();", false);
}

在aspx页面:

 function callCheckMethod() {
                 var confirm_value = document.createElement("INPUT");
                 confirm_value.type = "hidden";
                 confirm_value.name = "confirm_value";
                 if (confirm("Are you sure?")) {
                     confirm_value.value = "Yes";
                 } else {
                     confirm_value.value = "No";
                 }
                 document.forms[0].appendChild(confirm_value);
                 alert("<%= TestConfirmValue() %>");
                }

//

背后的代码
public string TestConfirmValue()
     {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == null) return null;
        if (confirmValue=="Yes")
        {
            //do something
        }
        return string.Empty;
    }

你不能。当您编写<% something %>时,它总是在创建页面之前在服务器上呈现。只有在所有asp标签被执行后,页面才会被发送到客户端,Javascript才会被调用。

有几种方法可以做到您正在尝试的事情,大多数都涉及ajax调用。查看"PageMethods",它是一种从客户端Javascript调用服务器端静态方法的方法。

http://www.ajaxtutorials.com/quickstart/ajax-tutorial-page-methods-in-asp-net/