Monday, May 30, 2011

How to open a pop up window in asp.net ?

A very good discussion at :

http://forums.asp.net/t/883647.aspx


Without Postback :
Button1.Attributes.Add("onclick", "window.open('www.microsoft.com'); return false;");

look at the following :

The onClick attribute is Javascript anyway, so it is wrong to also include the javascript: pseudo-protocol.

That is, the following is wrong:
    Button1.Attributes.Add("onclick", "javascript:window.open('www.microsoft.com'); return false;");

And the following is correct:
    Button1.Attributes.Add("onclick", "window.open('www.microsoft.com'); return false;");

We use the javascript: pseudo-protocol only when altering an href attribute, as by default that is an http:// protocol.

That is, the following is wrong:
    <a href="window.open('www.microsoft.com');">Visit Microsoft</a>

And the following is correct:
    <a href="javascript:window.open('www.microsoft.com');">Visit Microsoft</a>



However if you want deliberate postback , you can use something like :


<%@ Page Language="C#" %>
<%@ Import namespace="System.Text" %>
<script runat="server">
    void Button1_Click(object sender, EventArgs e)
    {
        // Do some other processing...
        StringBuilder sb = new StringBuilder();
        sb.Append("<script>");
        sb.Append("window.open('http://msdn.microsoft.com', '', '');");
        sb.Append("</scri");
        sb.Append("pt>");
        Page.RegisterStartupScript("test", sb.ToString());
    }
</script>
<html>
<head>
</head>
<body>
    <form runat="server">
        <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Go!"></asp:Button>
    </form>
</body>
</html>

No comments:

Post a Comment