Rectangle 27 3

The following code shows an aspx page on a modal JQuery dialog passing a post value (its a student Id stored in a server-side HiddenField)

<img alt="Previsiones" name="btnPrevisiones" id="btnButton" title="Dialog title"
src="imageFile.png" onclick="ShowStudentFullRecord(document.getElementById('<% =hiStudentId.ClientID%>').value)" />
function ShowStudentFullRecord(StudentId)
{
    var jsFileLocation = $('script[src*=yourJsFileName]').attr('src');
    jsFileLocation = jsFileLocation.replace('yourJsFileName.js', '');    
    $("#divStudentFullRecord")
        .load(jsFileLocation + "../SomeFolder/SomePage.aspx", {Id: StudentId })
        .dialog({
            autoOpen: false,
            show: "blind",
            hide: "explode",
            modal:true          
            });    
    $("#divStudentFullRecord").dialog( "open" );
    return false;        
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SomePage.aspx.cs" Inherits="SomePage" %>
  <label id="lblLabelId">
  <%= this.Something %></label>
protected string Something { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
         int studentId = Convert.ToInt32(Request.Form["Id"]);
         StudentFullRecord studentFullRecord = GetStudentFullRecord(studentId);
         this.Something = studentFullRecord.SomeImportantInformation; 
     }
}

I found this article to be extremely useful. It offers three approaches on loading aspx content into a page dinamically using jquery. It also explains how to pass parameters to the new page as post values.

Note that if you embed ASP.NET controls into the page generated you shouldnt expect them to behave like ASP.NET controls once returned and embedded as raw HTML. The base WebForm has no idea of the new content added to the page and so any form content embedded is treated as raw HTML only.

Follow the approach presented in the referred article under title ASPX Based Page Content. A very simple aspx with no server controls, just the html to render that little customer details popup of yours. To render that page on a JQuery dialog follow Haythem Tlili's answer.

Follow article's section Callback to the same Page and generate HTML to render just what you need in the same page

Tip 3 Its something like a delete confirmation popup

In this case is probable delete button will be on a Repeater or something similar. In your JQuery script, when referring to the popup trigger or the container, I suggest you:

  • Use a Label as trigger with CSS that makes it like a button.
  • Use a Panel as container.
  • When referring to these two on the jquery script do it like this: $("#<%= lblTrigger.ClientID %>").click(function(). With this there wont be id madness because of the Repeater thing.

Tip 4 You just want that independent aspx page on that dialog.

You could put an iFrame on a page (html or aspx) and use $.load to get that page. You need to understand that iFrame has some issues and you should use it only if its worth. Don't use this escenario if you expect to have significative comunication between the original page and the one loaded in the iFrame.

asp.net - How to load an ASPX page into a JQuery dialog box - Stack Ov...

jquery asp.net dialog modal-dialog
Rectangle 27 3

The following code shows an aspx page on a modal JQuery dialog passing a post value (its a student Id stored in a server-side HiddenField)

<img alt="Previsiones" name="btnPrevisiones" id="btnButton" title="Dialog title"
src="imageFile.png" onclick="ShowStudentFullRecord(document.getElementById('<% =hiStudentId.ClientID%>').value)" />
function ShowStudentFullRecord(StudentId)
{
    var jsFileLocation = $('script[src*=yourJsFileName]').attr('src');
    jsFileLocation = jsFileLocation.replace('yourJsFileName.js', '');    
    $("#divStudentFullRecord")
        .load(jsFileLocation + "../SomeFolder/SomePage.aspx", {Id: StudentId })
        .dialog({
            autoOpen: false,
            show: "blind",
            hide: "explode",
            modal:true          
            });    
    $("#divStudentFullRecord").dialog( "open" );
    return false;        
}
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SomePage.aspx.cs" Inherits="SomePage" %>
  <label id="lblLabelId">
  <%= this.Something %></label>
protected string Something { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
     if (!IsPostBack)
     {
         int studentId = Convert.ToInt32(Request.Form["Id"]);
         StudentFullRecord studentFullRecord = GetStudentFullRecord(studentId);
         this.Something = studentFullRecord.SomeImportantInformation; 
     }
}

I found this article to be extremely useful. It offers three approaches on loading aspx content into a page dinamically using jquery. It also explains how to pass parameters to the new page as post values.

Note that if you embed ASP.NET controls into the page generated you shouldnt expect them to behave like ASP.NET controls once returned and embedded as raw HTML. The base WebForm has no idea of the new content added to the page and so any form content embedded is treated as raw HTML only.

Follow the approach presented in the referred article under title ASPX Based Page Content. A very simple aspx with no server controls, just the html to render that little customer details popup of yours. To render that page on a JQuery dialog follow Haythem Tlili's answer.

Follow article's section Callback to the same Page and generate HTML to render just what you need in the same page

Tip 3 Its something like a delete confirmation popup

In this case is probable delete button will be on a Repeater or something similar. In your JQuery script, when referring to the popup trigger or the container, I suggest you:

  • Use a Label as trigger with CSS that makes it like a button.
  • Use a Panel as container.
  • When referring to these two on the jquery script do it like this: $("#<%= lblTrigger.ClientID %>").click(function(). With this there wont be id madness because of the Repeater thing.

Tip 4 You just want that independent aspx page on that dialog.

You could put an iFrame on a page (html or aspx) and use $.load to get that page. You need to understand that iFrame has some issues and you should use it only if its worth. Don't use this escenario if you expect to have significative comunication between the original page and the one loaded in the iFrame.

asp.net - How to load an ASPX page into a JQuery dialog box - Stack Ov...

jquery asp.net dialog modal-dialog
Rectangle 27 2

Having been down the road of Ajax Control Toolkit, I would recommend moving on to jQuery or some other javascript framework. While I understand the desire to "control it from codebehind," because it seems easier at first, trying to wrap client-side functionality in a server-side control usually is more trouble than it's worth.

Even in the simplest case, the the amount of javascript code needed to create a modal popup in jQuery (e.g.) is less than with Ajax Control Toolkit MPE. For example, I like the jQuery plugin SimpleModal. The code to turn a div into a modal popup using SimpleModal with default options is this:

<script type="text/javascript">
    function showPopup() {
        $('#<%=popupDivID.ClientID %>').modal({ appendTo: '#aspnetForm' });
    }
    </script>

Then you can just add that function to a click event, for example. And it's about a thousand times more flexible.

If you just don't like embedding javascript in your markup files, you can still technically control this all from codebehind by using ScriptManager to register the scripts and add events to controls.

ajax - Alternatives to modal popup extender in asp.net? - Stack Overfl...

asp.net ajax modalpopupextender
Rectangle 27 2

Your page is posting back because of the autopostback="true" on the checkbox, thus hiding the modal popup.

I'm sure you'd also like to know how to solve this.

Should check 3 in priority, a update panel should be put inside the modal pop up so the "calculation on each checkchanged event" wont initiate a full post-back.

asp.net - Problem with Ajax control toolikt Modal Pop control - Stack ...

asp.net ajaxcontroltoolkit modalpopupextender
Rectangle 27 1

Add custom attribute to the link, use its URL to load the PartialView from controller in the modal form.

@Html.ActionLink("View Clients", "Details", "Client", new { id = item.Id }, new { data_modal = "" })

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>
$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {        
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');
        });
        return false;
    });
});
public class ClientController : Controller
{
  public ActionResult Details(long id = 0)
    {
        Client client = db.Clients.Find(id);
        if (client == null)
        {
            return HttpNotFound();
        }
        return PartialView(client);
    }
}

c# - Open the view in popup in asp.net MVC action click - Stack Overfl...

c# jquery asp.net-mvc asp.net-mvc-4
Rectangle 27 1

Add custom attribute to the link, use its URL to load the PartialView from controller in the modal form.

@Html.ActionLink("View Clients", "Details", "Client", new { id = item.Id }, new { data_modal = "" })

<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
    <div class="modal-dialog">
        <div class="modal-content">
            <div id='myModalContent'></div>
        </div>
    </div>
</div>
$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {        
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');
        });
        return false;
    });
});
public class ClientController : Controller
{
  public ActionResult Details(long id = 0)
    {
        Client client = db.Clients.Find(id);
        if (client == null)
        {
            return HttpNotFound();
        }
        return PartialView(client);
    }
}

c# - Open the view in popup in asp.net MVC action click - Stack Overfl...

c# jquery asp.net-mvc asp.net-mvc-4
Rectangle 27 1

I have disabled the popup blocker, but the problem is stil occuring

c# - open page in new tab asp.net - Stack Overflow

c# asp.net redirect response
Rectangle 27 2

There is no way of opening the default browser action popup programmatically. A work around is use content scripts to open a modal or a lightbox and show the contents of your popup.

Another way would be - within the clickhandler of your context menu item, create a new tab and make it inactive and then pass that tab to chrome.windows.create api to create a new popup window.

chrome.tabs.create({
      url: chrome.extension.getURL('popup.html'),
      active: false
  }, function(tab) {
      // After the tab has been created, open a window to inject the tab
      chrome.windows.create({
          tabId: tab.id,
          type: 'popup',
          focused: true
      });
  });

It is just a work around. Hope it helps.

google chrome - Open extension popup when click on context menu - Stac...

google-chrome google-chrome-extension
Rectangle 27 1

Have you looked at the Ajax Control Toolkit on CodePlex. Ajax Control Toolkit It has several very useful controls that are very easy to implement. The toolkit includes a modal popup control as well as a popup control. In the link I gave you are all the instruction on how to download and use the toolkit.

Another option if you have access to it is Telerik controls. Their Ajax controls include what they call a radWindow which also works very well. You can read about it here. The drawback to Telerik is it is quite expensive.

I have used both and they work very well.

ajax - Alternatives to modal popup extender in asp.net? - Stack Overfl...

asp.net ajax modalpopupextender
Rectangle 27 1

here is what I did to re-create your issue. I've created a web page with a modal popup extender.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ModalPopExample.aspx.cs" Inherits="WebApp.ModalPopup.ModalPopExample" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Page</title>
    <style type="text/css">
        .hide
        {
            display:block;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
        <ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </ajaxToolkit:ToolkitScriptManager>
        <asp:Panel ID="Panel1" CssClass="hide" runat="server" BorderColor="Red" BorderStyle="Dashed" BorderWidth="3px">
            Are you sure?
            <br />
            <asp:Button ID="btnok" runat="server" Text="OK" />
            <asp:Button ID="btncancel" runat="server" Text="Cancel" />
        </asp:Panel>
        <asp:Button ID="btnShow" runat="server" Text="Show Modal" />
        <asp:Image ID="Image1" ImageUrl="~/image_loader.ashx" runat="server" />
        <ajaxToolkit:ModalPopupExtender ID="btnShow_ModalPopupExtender" DropShadow="true" OkControlID="btnok" CancelControlID="btncancel" PopupControlID="Panel1" runat="server" DynamicServicePath="" Enabled="True" TargetControlID="btnShow">
        </ajaxToolkit:ModalPopupExtender>        
    </form>
    <script>
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_pageLoaded(function () {
            console.log('loaded');
        });
    </script>
</body>
</html>

Notice that the image is loaded via a handler file (ashx):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;

namespace WebApp.ModalPopup
{
    /// <summary>
    /// Summary description for image_loader
    /// </summary>
    public class image_loader : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/jpg";
            var imagePath = context.Server.MapPath("~/images/windows_xp_bliss-wide.jpg");
            Thread.Sleep(20000);
            context.Response.TransmitFile(imagePath);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

The popup flickers for a while. The most simple workaround you can do is hide the element at first itself (via css) and some javascript is required to remove that css when the web page if fully loaded.

<style type="text/css">
        .hide
        {
            display:none;
        }
    </style>

When you ajax client scripts all finish loading...find the control and remove the above class on the element.

<script>
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_pageLoaded(function () {
        console.log('loaded');
        var div = document.getElementById('Panel1');
        div.className = '';
    });
</script>

My doubt is, I am writing __doPostBack("", ""); for getting postback onclick of treeview in another page( ascx usercontrol). But we are displaying the ascx page in another(main) page via modelpopupextender.Now the __doPostBack("", ""); method is applying for main page not for that ascx page I guess.. What do you say ??

Ascx is supposed to be thought of something like a "reusable" component. Its not a page in itself. Anyway I don't quite follow how your problem has run into page postbacks. It was never part of the original question. Seems like you need to open another question out here.

A word of advice: don't just post a question because you are stuck. Try to present a "fake" problem which "models" your actual problem. It helps us re-create the issue you are facing and also helps people out here to provide better answers. And when you are at it, chances are that you might itself figure out a solution. :)

c# - asp ModalPopupExtender is getting closed when page is getting pos...

c# javascript asp.net ajax postback
Rectangle 27 5

In this case you can use a custom action filter attribute that opens a popup if the user is not authorized. In this action filter just check if user is logged in and add a boolean value to the ViewData collection. Aplly the attribute on the controller's action. Then in the master page add conditional rendering of code that opens the popup.

The code for the attribute:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class PopupAuthorizeAttribute : AuthorizeAttribute
{
    private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        validationStatus = this.OnCacheAuthorization(new HttpContextWrapper(context));
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = false;
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }
        if (this.AuthorizeCore(filterContext.HttpContext))
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            cache.SetProxyMaxAge(new TimeSpan(0L));
            cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), null);
            isAuthorized = true;
        }

        filterContext.Controller.ViewData["OpenAuthorizationPopup"] = !isAuthorized;
    }
}

In the master page or other common view add conditional rendering:

<% if((bool)(ViewData["OpenAuthorizationPopup"] ?? true)) { %>
 ...Your code to open the popup here...
<% } %>

jquery - ASP.NET MVC Authorize Attribute to launch a modal? - Stack Ov...

jquery asp.net-mvc model-view-controller modal-dialog
Rectangle 27 171

You can access parent window using 'window.opener', so, write something like the following in the child window:

<script>
    window.onunload = refreshParent;
    function refreshParent() {
        window.opener.location.reload();
    }
</script>

I didn't know window.opener, thanks! I always put the caller window in a variable in the contentWindow of the child. :-/

this is fantastic. So easy. So straight forward. I saw another answer with window.opener that was awful.

If you don't control JavaScript on the child page (e.g. OAuth flow) then you will need to check popupWindow.closed using setInterval like in @Zuul's solution.

javascript - Open popup and refresh parent page on close popup - Stack...

javascript html javascript-events
Rectangle 27 1

i think you can set your modal to be loaded at the same time of your body page which mean whenever you run that page it will open up with an open modal follow this link How to make modal dialog open at page load in bootstrap

Thanks Jarel, you have definately pointed me in the right direction. Managaed to get the modal working as required, still working on the timer but ill get there!

javascript - After record insert, reload form page & automatically sho...

javascript jquery bootstrap-modal
Rectangle 27 1

i think you can set your modal to be loaded at the same time of your body page which mean whenever you run that page it will open up with an open modal follow this link How to make modal dialog open at page load in bootstrap

Thanks Jarel, you have definately pointed me in the right direction. Managaed to get the modal working as required, still working on the timer but ill get there!

javascript - After record insert, reload form page & automatically sho...

javascript jquery bootstrap-modal
Rectangle 27 1

Use an ajax call to return the partial view and add it to the DOM.

var url = '@Url.Action("Details", "Client")';

$('selector').load(url, { id: 1 });

You can enhance your answer and add an id/class to that action link and use that as selector, this will make the answer more useful:)

It's not clear on how you are managing the ID's on the main page as there was no HTML markup. The 'selector' is the element you want to fill with the partial view data. Pass the id of the Client (via a click event for example) you want to load into that selector.

c# - Open the view in popup in asp.net MVC action click - Stack Overfl...

c# jquery asp.net-mvc asp.net-mvc-4
Rectangle 27 1

Use an ajax call to return the partial view and add it to the DOM.

var url = '@Url.Action("Details", "Client")';

$('selector').load(url, { id: 1 });

You can enhance your answer and add an id/class to that action link and use that as selector, this will make the answer more useful:)

It's not clear on how you are managing the ID's on the main page as there was no HTML markup. The 'selector' is the element you want to fill with the partial view data. Pass the id of the Client (via a click event for example) you want to load into that selector.

c# - Open the view in popup in asp.net MVC action click - Stack Overfl...

c# jquery asp.net-mvc asp.net-mvc-4
Rectangle 27 2

You can add a class to the body tag when the popup is open to hide the scrollbar, and remove it when the popup goes away, then your background should be position:fixed and the height should be the window.height() (get it dynamically with JS), and also be overflow:auto.

What happens with all that is that, if the popup is taller than the background, you get a nice scroll bar on the right, and because your body scroll bar is hidden, you see only that one. Also, the page itself doesn't scroll. That's the way Facebook does it with their picture viewer.

asp.net - How can I make the modal popup scroll its contents with the ...

asp.net ajaxcontroltoolkit modalpopupextender sizing
Rectangle 27 25

The pop-up window does not have any close event that you can listen to.

On the other hand, there is a closed property that is set to true when the window gets closed.

You can set a timer to check that closed property and do it like this:

var win = window.open('foo.html', 'windowName',"width=200,height=200,scrollbars=no");   
var timer = setInterval(function() {   
    if(win.closed) {  
        clearInterval(timer);  
        alert('closed');  
    }  
}, 1000);

Somewhat hackish but I think using a timer will work the best across all browsers.

This is also the best solution if the popup has several pages before it closes, as the onunload event is triggered only after the user navigates away from the first page.

javascript - Open popup and refresh parent page on close popup - Stack...

javascript html javascript-events
Rectangle 27 23

I put the following javascript in the page header and it seems to work. It detects when the browser does not support showModalDialog and attaches a custom method that uses window.open, parses the dialog specs (height, width, scroll, etc.), centers on opener and sets focus back to the window (if focus is lost). Also, it uses the URL as the window name so that a new window is not opened each time. If you are passing window args to the modal you will need to write some additional code to fix that. The popup is not modal but at least you don't have to change a lot of code. Might need some work for your circumstances.

<script type="text/javascript">
  // fix for deprecated method in Chrome 37
  if (!window.showModalDialog) {
     window.showModalDialog = function (arg1, arg2, arg3) {

        var w;
        var h;
        var resizable = "no";
        var scroll = "no";
        var status = "no";

        // get the modal specs
        var mdattrs = arg3.split(";");
        for (i = 0; i < mdattrs.length; i++) {
           var mdattr = mdattrs[i].split(":");

           var n = mdattr[0];
           var v = mdattr[1];
           if (n) { n = n.trim().toLowerCase(); }
           if (v) { v = v.trim().toLowerCase(); }

           if (n == "dialogheight") {
              h = v.replace("px", "");
           } else if (n == "dialogwidth") {
              w = v.replace("px", "");
           } else if (n == "resizable") {
              resizable = v;
           } else if (n == "scroll") {
              scroll = v;
           } else if (n == "status") {
              status = v;
           }
        }

        var left = window.screenX + (window.outerWidth / 2) - (w / 2);
        var top = window.screenY + (window.outerHeight / 2) - (h / 2);
        var targetWin = window.open(arg1, arg1, 'toolbar=no, location=no, directories=no, status=' + status + ', menubar=no, scrollbars=' + scroll + ', resizable=' + resizable + ', copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
        targetWin.focus();
     };
  }
</script>

It seems IE has same problems too. If we override the function by removing the first if, it works in all 3 major browsers.

Any sample in jsfiddle ? jsfiddle.net/grj4x5k9 sample using HTML5 dialog (with this problems)

javascript - How can I make window.showmodaldialog work in chrome 37? ...

javascript jquery asp.net google-chrome cross-browser