1

On a web application, I need to do some conditional logic and then based on that, possibly show a dialog box. Here's what I need to do:

  1. Button pressed, submitting two IP Addresses
  2. Check if these addresses are 'in use'
    1. If they are:
      1. display confirm box
        1. If "OK" is pressed, call C# function
        2. Otherwise, done
    2. If they're not:
      1. Call C# function

When the button is pressed, it calls the clicked method btnLinkConnect_Click() in the C# codebehind. This then checks for addresses 'in use'. Stepping through with the debugger, this all works fine, but if addresses are 'in use', a javascript script is supposed to run to display the box:

<script type="text/javascript">
    function askForOverride(station1, station2) {
        var answer = confirm("Station(s):" + PageMethods.GetActiveStations(station1, station2) + "is/are in use. Override?");
        if (answer) {
            PageMethods.uponOverride(station1, station2);
        }
    }
</script>

But how can I get this script to run from the C# page? I've looked at ClientScript.RegisterStartupScript(), but I couldn't get it to work, and it appears not to be able to work inside the conditionals. I've looked at ajax, but I couldn't understand exactly how to call it from the C# codebehind.

What is the best way to call this script, or obtain the same result, and how should I go about it?

8
  • Are you aware that JavaScript executes on the client-side, in the browser, and that the "code-behind" executes on the server-side? Commented Jul 30, 2013 at 14:41
  • 1
    Have a look at this: msdn.microsoft.com/en-us/library/z9h4dk8y.aspx Commented Jul 30, 2013 at 14:41
  • @DanielMann - yes I am Commented Jul 30, 2013 at 14:42
  • @SamHood - I did try that too, but I couldn't get it to work. Can it be done in a function other than PageLoad()? I've never seen it done anywhere else Commented Jul 30, 2013 at 14:45
  • 1
    As far as I know you can put it anywhere before the page is sent to the client. What was the problems/errors you were facing? Commented Jul 30, 2013 at 14:49

3 Answers 3

1

This may work, add some client events for button click based on condition. Please refactor if necessary

 protected void btnSumbit_Click(object sender, EventArgs e)
        {       
            //call some function to verify IP entered by user
            bool isExistingIp = VerifyIp(txtIP.Text); 
            if (isExistingIp)
            {
                // event argument PASSED when user confirm to override from client side
                string isoverride = Request.Form["__EVENTARGUMENT"]; 
                if (string.IsNullOrEmpty(isoverride))
                {                
                    //register script if user hasn't confirmed yet
                    this.ClientScript.RegisterStartupScript(this.GetType(), "displaywarning", "displaywarning();", true);
                    Page.GetPostBackEventReference(btnSumbit);
                }
                else
                {
                    //continue with functionality
                }

            }
            else
            {
                //continue with functionality
            }
        }

On client side add javascript to display warning and do a post back

 function displaywarning() {
            var isOverride = window.confirm("do you want to override");
            if (isOverride) {
                __doPostBack('<%=btnSumbit.ClientID%>', 'override');
            }
        }
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work. When I step through with the debugger, it does get to the ClientScript.RegisterStartupScript line, but nothing happens
1

You can easily do this with jQuery AJAX calls.

ASPX

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/ui-lightness/jquery-ui.css" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

<script type="text/javascript">
$(document).ready(function () {
$('body').on('click', '.performsMyClickAction', function () {
$.ajax({
    type: "POST",
    url: "BlogPost.aspx/TestIP",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
        if (result.d = 1) //In use
        {
            $("<div>State your confirm message here.</div>").dialog({
                resizable: false,
                height: 210,
                modal: true,
                buttons: {
                    "Ok": function () {
                        __doPostBack('<%= upnl.ClientID %>', 'InUse ');
                                        $(this).dialog("close");
                                    },
                                    "Cancel": function () {
                                        $(this).dialog("close");
                                    }
                                }
                            });
                        } else {
                            __doPostBack('<%= upnl.ClientID %>', 'NotInUse ');
                        }
                    }
                });
            });
});
</script>          

<body>
<form id="form2" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <asp:UpdatePanel ID="UpdatePanel1" runat="server" OnLoad="upnl_Load">
        <ContentTemplate>
            <div>
                 <asp:Button CssClass="performsMyClickAction"  Text="Test IP" ID="Button3" runat="server" />
            </div>
</ContentTemplate>
    </asp:UpdatePanel>
</form>
</body> 

C#

protected void upnl_Load(object sender, EventArgs e)
{
    string eventTarget = (this.Request["__EVENTTARGET"] == null) ? string.Empty : this.Request["__EVENTTARGET"];

    if (string.IsNullOrEmpty(eventTarget)) return;

    var arg = Request.Params.Get("__EVENTARGUMENT");
    if (arg == null) return;

    if (!string.IsNullOrEmpty(arg.ToString()))
    {
        if (arg.ToString().IndexOf("InUse") > -1)
        {
            //Call C# function for in use.
        }

        if (arg.ToString().IndexOf("NotInUse") > -1)
        {
            //Call C# function for not in use.
        }
    }
}

[WebMethod]
public static string TestIP()
{
    //Check for IP status
    if (true)
        return "1";

    //else
    //return "0";
}

Hope this will help you.

Comments

-1

Have a look at ClientScriptManager.RegisterStartupScript, i think this should work

1 Comment

I already tried CS.RSS as well as CSM.RSS, but couldn't get it to work. If you could add more details to show how, that would be great

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.