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 '' 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="">
<head id="Head1" runat="server">
    <title>Test Page</title>
    <script runat="server">
        public string RootUrl
                Uri requestUri = Context.Request.Url;
                HttpRequest request = Context.Request;
                string rootUrl = string.Format("{0}{1}{2}{3}{4}",
                    requestUri.IsDefaultPort ? 
                        string.Empty : string.Format(":{0}", requestUri.Port),
                return rootUrl.EndsWith("/") ? rootUrl : 
                        string.Format("{0}/", rootUrl);
        private string script = @"
        protected void OpenWindow(object sender, EventArgs e)
            string page = string.Concat(
                  this.RootUrl, ((LinkButton)sender).CommandArgument);
            /// Check your condition
            bool myCondition = true;
            if (myCondition)
                    string.Format(this.script, page),
    <form id="form1" runat="server">
            Text="Open a Window" 
            CommandArgument="Tutorials/Rocky/Training.pdf" />

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...