0

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;

    }
1
  • Code Behind executes on the server before code is sent to the client . The JavaScript isn't executed until it is sent to the client. By that time, your TestConfirmValue() has already executed and returned null. Sounds like you may need to look into using AJAX. Commented Jun 13, 2014 at 19:00

1 Answer 1

1

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.