简体   繁体   中英

Executing the javascript code properly from asp.net

I'm trying to get the confirm_value from TestConfirmValue() method in the code behind but when the javascript function callCheckMethod() is called, the last line of the function

alert("<%= TestConfirmValue() %>") is called before anything else. So, TestConfirmValue() is called first and confirm_value is always null.

How can I get the confirm_value to be set from the javascript function first before TestConfirmValue() is called?

On Code behind:

      protected override void OnPreRender(EventArgs e)
{

        ClientScript.RegisterStartupScript(GetType(), "Javascript", "callCheckMethod();", false);
}

On aspx page:

 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() %>");
                }

//Code Behind

public string TestConfirmValue()
     {
        string confirmValue = Request.Form["confirm_value"];
        if (confirmValue == null) return null;

        if (confirmValue=="Yes")
        {
            //do something
        }

        return string.Empty;

    }

You can't. When you write <% something %> , it is always rendered on the server, before your page is even created. Only after all asp tags are executed, the page will be sent to the client and the Javascript will be called.

There are several ways to do what you are trying, most involve ajax calls. Look into "PageMethods", which is a way to call server-side static methods from the client Javascript.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM