简体   繁体   中英

How to add dynamic javascript alert box in asp.net?

Please help me .I am new to asp.net .How can I write dynamic javascript in asp.net web forms ? What I want to do is as the following code .

The follow code is in button click event of server side ,written in c# . Please help me .

if(Email.send()){
//show javascript alert box
}else{
//show javascript alert box
}

Create a webmethod that you call via AJAX and pop the javascript alert based on the result of that function.

example (in your .aspx page):

        function doSomething() {
            $.ajax({
                type: "POST",
                url: "Do_Something.aspx/DoSomething",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response);
                }
            });

In Do_Something.aspx.cs:

    [WebMethod]
    public static string DoSomething()
    {
        if (Email.Send)
        {
            return "success";
        }
        return "not a success";
    }

With asp.net, all server side code is going to run before the Web Page is sent to the end user, and then the result of that code is injected into the HTML/Javascript.

Also, when injecting server side code into javascript, you are required to do it within a string literal (quotes).

So, if you have in a javascript click handler:

if ("@Email.Send()") {
    // stuff
} else {
    // other stuff
}

The Email.Send() command will run, and the results of that command will be placed in the Html. If your Send function returned a boolean, which I am assuming it does, the Html returned to your end user would look like this:

if ("true") {
    // stuff
} else {
...

I'm assuming this is not your desired outcome. The correct way to do this, is to trigger another command on your server via AJAX inside your click command, and use the result of that AJAX command for your logic. It would look like this:

function clickHandler() {
    $.ajax({
        type: "POST",
        url: "UrlToYourServerSideAction",
        data: {
            WebParam1: "value",
            WebParam2: "value"
        },
        success: function (response) {
            if (response == "true") {
                // code if Web Method returns true
            } else {
                // code if Web Method returns false
            }
        }
    });
}

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