Monday, February 22, 2010

Opening a new window after executing some code in a postback - Asp.Net

If we need to do a postback and then open a new window( equvalent to target = _blank) if a conditon is true, I think if we register a 'window.open(....)' script block on the click event of the link button when condition is true, it seems it opens the new window on your postback.
PS: RootUrl is bit critical here: I have tested RootUrl property. However you can use it if you want, but if you get problems please have a web.config configrued value for root url. We never know where it go wrong. It might work on local but when you deploy it to live or a in some extrem conditions it might stop working.

Here is an example:
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Test Page</title>
    <script runat="server">
        public string RootUrl
        {
            get
            {
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.Scheme,
                    Uri.SchemeDelimiter,
                    requestUri.Host,
                    requestUri.IsDefaultPort ? 
                        string.Empty : string.Format(":{0}", requestUri.Port),
                    request.ApplicationPath);
                return rootUrl.EndsWith("/") ? rootUrl : 
                        string.Format("{0}/", rootUrl);
            }
        }
        private string script = @"
            window.open('{0}','',
                'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
        ";
        protected void OpenWindow(object sender, EventArgs e)
        {
            string page = string.Concat(
                  this.RootUrl, ((LinkButton)sender).CommandArgument);
            ///
            /// Check your condition
            ///
            bool myCondition = true;
            if (myCondition)
            {
                Page.ClientScript.RegisterClientScriptBlock(
                    this.GetType(),
                    this.GetType().Name,
                    string.Format(this.script, page),
                    true);
            }
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:LinkButton 
            runat="server" 
            ID="lnkButton" 
            OnClick="OpenWindow" 
            Text="Open a Window" 
            CommandArgument="Tutorials/Rocky/Training.pdf" />
    </form>
</body>
</html>
 

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...