0

In my C# i used this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ASPConnectionString"].ConnectionString);


    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();

    }
    protected void SubmitButtonClick(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("INSERT INTO Students (Name,City,Age) Values(@Name,@City,@Age)", con);
        cmd.Parameters.AddWithValue("@Name", NameText.Text);
        cmd.Parameters.AddWithValue("@City", CityText.Text);
        cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(AgeText.Text));
        cmd.ExecuteNonQuery();
        con.Close();
        SuccessMessage.Visible = true;
        SuccessMessage.Text = "Successfully Inserted data";
        CityText.Text = "";
        NameText.Text = "";
        AgeText.Text = "";

        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "showalert();", true);

    }

}

And my ASPX:

   <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .auto-style1
        {
            text-align: center;
        }

        .auto-style2
        {
            width: 163px;
        }

        .auto-style3
        {
            text-align: center;
        }

        .auto-style4
        {
            font-size: large;
        }

        .auto-style5
        {
            text-align: right;
        }

        .auto-style6
        {
            width: 112px;
        }

        .auto-style7
        {
            text-align: center;
            width: 163px;
        }
    </style>


</head>
<body>



<div id="dialog" title="Basic dialog">
  <p>insert succussfly</p>
</div>

<button id="opener">Open Dialog</button>

    <form id="form1" runat="server">


        <div>

            <div class="auto-style3">
                <span class="auto-style4">Inserting Data to DB<br />
                </span>
            </div>
            <table align="center" style="width: 41%; height: 179px;">
                <tr>
                    <td class="auto-style5">Name:</td>
                    <td class="auto-style6">
                        <asp:TextBox ID="NameText" runat="server"></asp:TextBox>
                    </td>
                    <td class="auto-style2">
                        <asp:RequiredFieldValidator ID="NameValidation" runat="server"
                            ControlToValidate="NameText" ErrorMessage="Name is reqiured"
                            Style="color: #FF0000; text-align: left">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style5">City:</td>
                    <td class="auto-style6">
                        <asp:TextBox ID="CityText" runat="server"></asp:TextBox>
                    </td>
                    <td class="auto-style2">&nbsp;</td>
                </tr>
                <tr>
                    <td class="auto-style5">Age:</td>
                    <td class="auto-style6">
                        <asp:TextBox ID="AgeText" runat="server"></asp:TextBox>
                    </td>
                    <td class="auto-style2">
                        <asp:RangeValidator ID="AgeValidation" runat="server"
                            ControlToValidate="AgeText" Display="Dynamic"
                            ErrorMessage="Age need to be between 20 to 50" MaximumValue="50"
                            MinimumValue="20" Style="color: #CC0000">*</asp:RangeValidator>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                            ControlToValidate="AgeText" Display="Dynamic" ErrorMessage="Age is required"
                            Style="color: #CC0000">*</asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td class="auto-style1" colspan="2">
                        <asp:Button ID="SubmitButton" runat="server" OnClick="SubmitButtonClick"
                            Style="text-align: center" Text="Insert" />
                    </td>
                    <td class="auto-style7">&nbsp;</td>
                </tr>
            </table>

            <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                Style="color: #CC0000" />

            <asp:Label ID="SuccessMessage" runat="server" Text="" Visible="False"></asp:Label>

        </div>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:ASPConnectionString %>"
            SelectCommand="SELECT * FROM [Students]"></asp:SqlDataSource>
    </form>

    <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
    <script type="text/javascript">

            $(function () {
                $("#dialog").dialog({
                    autoOpen: false,
                    show: {
                        effect: "blind",
                        duration: 1000
                    },
                    hide: {
                        effect: "explode",
                        duration: 1000
                    }
                });

                function showalert() {
                    $(document).ready(function () {
                        $("#dialog").dialog("open");
                    });
                }
        /*        $("#opener").click(function () {
                    $("#dialog").dialog("open");
                });*/
            });

    </script>
</body>
</html>

I want to open the dialog after postback and it runs the alert function after finished the insert. Can you help me thanks. I'm now getting showalert() is not defined.

1
  • what's wrong? What's your question? Are you getting javascript errors? Commented Oct 24, 2014 at 16:32

4 Answers 4

1

Since you have used javascript closure , and inside that you have showalert, so it will not be accessible to outside. For more info on closure read this - http://www.w3schools.com/js/js_function_closures.asp and How do JavaScript closures work?

To make it work, please use this.

function showalert() {
$(function () {
    $("#dialog").dialog("open");
});
}

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "script", "showalert()", true);

NOTE - The code you are using SqlCommand cmd = new SqlCommand("INSERT INTO Student .... is prone to SQL injection , you need to use parameterized query for this.

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

7 Comments

I'm getting Uncaught TypeError: undefined is not a function
Make sure you have included jquery and jquery.ui js files.
@Taha, updated code, try this!, i think you are definitely missing jquery and jquery.ui library after checking updated code, please add those to aspx , then it will work, there is no issue with the code now.
I'm getting : Uncaught ReferenceError: showalert is not defined
Where should i add the jquery and jquery.ui library? When i put it at header i get jquery is not defined but when i put it in body it don't show that error message. i use this <link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
|
1

Your code is working fine. I think you might be missing jquery and/or jqueryui.

Or you have script error in other part of your code. Create a stand along aspx page and test with the following code.

enter image description here

<asp:Button ID="SubmitButton" runat="server"
    Text="Submit"
    OnClick="SubmitButton_Click" />
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            autoOpen: false,
            show: {
                effect: "blind",
                duration: 1000
            },
            hide: {
                effect: "explode",
                duration: 1000
            }
        });
    });
    function showalert() {
        $(function () {
            $("#dialog").dialog("open");
        });
    }
</script>
<div id="dialog" title="Basic dialog">
    <p>insert successfully</p>
</div>

Code Behind

protected void SubmitButton_Click(object sender, EventArgs e)
{
    ScriptManager.RegisterStartupScript(this, this.GetType(), 
        "script", "showalert();",  true);
}

1 Comment

Nice catch on the OP's question. That could be part of the problem.
0

Your on the proper approach, you code actually looks correct (Aside you use jQuery UI Dialog rather than Alert. Here would be some items to help you a bit more.

function Submit() {
     if(!confirm("Are you sure you would like to submit?")) {
          return false;
     } else { 
          return true; 
     }
}

That particular function will act for a confirmation on the on click event. Then for your front-end you would have:

<asp:Button 
      id="btnSubmit" runat="server" 
      OnClientClick="return Submit();" 
      OnClick="btnSubmit_Click" />

So when you hit the button, it will bring a confirm dialog up for the user. On the code behind:

protected void btnSubmit_Click(object sender, EventArgs e)
{
     // Do your database stuff, then to call Javascript from code behind.
     ScriptManager.RegisterStartupScript(this.GetType(), "Alert", "ResponseToClient();", true);
}

Your calling a function called ResponseToClient and your wrapping it in the <script> tag. So lets build our function:

function ResponseToClient() {
     alert("You successfully saved.");
}

Though the example is primitive it should provide more detail and information for you to make it useful for the User Experience correctly. Important: I usually if I do a call from code behind to front-end, I use a function. It is often far more reliable and doesn't always error in the closure of your script tag. Hope this gets you started.

Noticed: Your code could be subject to SQL Injection. You should use parameter approach:

string query = @"SELECT * FROM [Table] WHERE ([Column] = @Id);";
using(SqlConnection connection = new SqlConnection(...))
     using(SqlCommand command = new SqlCommand(query, connection))
     {
          command.Parameters.AddWithValue("@Id", parameter); // OR
          command.Parameters.Add("@Id", SqlDbType.Int).Value = parameter;
     }

That is the proper approach, as it implements IDispose and properly parameterizes your query.

Comments

0

To add to Arindam Nayak's comment, your showalert function is only valid inside the scope of the anonymous function defined at the top of your script : $(function () { ... }.

You just need to move the definition of the showalert function after the first function for it to work:

$(function () { $("#dialog").dialog({ autoOpen: false, show: { effect: "blind", duration: 1000 }, hide: { effect: "explode", duration: 1000 } }); });

function showalert() {
    $(function () {
        $("#dialog").dialog("open");
    });
}

1 Comment

I'm getting Uncaught TypeError: undefined is not a function

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.