2 Modal Popups - properties being switched when ajax script runs - asp.net

While I was typing this I figured out what was causing my issue, but I haven't figured out why it was causing an issue, and it seems strange to me. Maybe someone could explain... Here is my situation (question is at the bottom):
I have 2 modal popups.
PopupControlID as follows:
popup1
popup2
calling from server side code:
popup1.Show() 'works fine
popup2.Show() 'works fine
at some point though:
popup1.Show() 'inspecting on server side all properties definitely belong to
'popup1, but when the ajax .js is triggered, popup2
'property values are being used
Everything was set up properly for these controls to run, but something outside of their setup was cauing a problem.
In page_load I was setting the target popup control for popup2 (which was a div) to .Visible = False. When I noticed this code I deleted it because it was unnecessary since I knew the target control was hidden using style="display:none;". After removing this, I ran the code, not expecting this to fix the bug, but the conflict disappeared. I do not understand how this could affect my pop ups in such a manner.
THE QUESTION:
Does anybody know why popup1.Show() would go ahead and use popup2's properties instead of it's own in the ajax script, just because at some point in the code the target control of popup2 was set to .visible = false?

In replicating my issue it seems the answer is as simple as this:
Any time you set a control to .Visible = "False" that is also the PopupControlID of a modal popup extender it will cause an error and the page will not load. I feel kinda stupid for now realizing this up front, a real "duh" moment...
Anyway, pretty basic stuff when I realized what was happening. Here is an article related to this issue:
http://blog.matthewdoyle.net/2008/10/13/visiblefalse-vs-displaynone/

Related

Message Box in ASP.NET hindering the layout

I am displaying a message in my ASP.NET from code-behind using this:
Response.Write("<script>alert('Hello')</script>");
When the OK button is pressed on the message box, the whole layout of the web page shifts a little towards the right direction. What is wrong? Is something else to be added?
private void alert(string Msg)
{
Response.Write("<script language = 'javascript'>window.alert('" + Msg + "')</script>");
}
try the previos method ..
if u want cool messages try the following link:
Produce "toast" messages like StackOverflow
Could it be that the scrollbars get visible when the popup is active? It has happened a few times for me and I thought the style was getting messed up, but it was just the scrollbars becoming visible and disappearing :) They shift the page a little.
At the risk of getting dinged for providing an additional answer to an "answered" question, I think others coming across this question should be advised as a matter of course that hard-coding HTML strings through Response.Write in ASP.NET applications is an increasingly frowned-upon practice for precisely the reason you've observed - the page rendering emits HTML that has no way of accounting for interjected Response.Write statements, risking all manner of layout grief.

RadioButtons, ListViews, and Grouping, oh my!

I've got a project I'm working on where I need to put a RadioButton inside a ListView, and have them all have the same GroupName. (can't use RadioButtonList, long story).
Anyway, this seems to be a well known bug in .NET, so I've implemented the solution found here:
ASP.NET RadioButton messing with the name (groupname)
This works perfectly, but with one small bug which undoubtedly will come back to bite me. If I click one radio button, and then click another while the javascript function is still running and has not completed; I can get 2 radiobuttons in the same group selected.
Any ideas? If you need clarification; leave me a comment and I'll update my post.
EDIT: I believe I fixed my own issue here. See my posted answer below.
Would something like this work?
if (!rbClicked)
rbClicked=True;
runJavascript();
rbClicked=False;
I admit I didn't do alot of research, but this is how I've usually solved this type of problem.
Turns out I was misguided here.
Later on in the page lifecycle; I was adding an additional onclick event that was overwriting the previous value.
In the following example:
var radiobutton = new System.Web.UI.WebControls.RadioButton();
radiobutton.Attributes.Add("onclick", "test1");
radiobutton.Attributes.Add("onclick", "test2");
the onlcick attribute is set to "test2"; test1 is lost.
I ended up fixing it by appending to the existing attribute; see below:
radiobutton.Attributes["onclick"] = string.Format("{0};{1}", radiobutton.Attributes["onclick"], "My Second Script");
This works without issue.

does showModalDialog interfere with ClientScript.RegisterStartupScript?

I'm showing a modal dialog via "window.showModalDialog(..." which happens in a vbscript function (the page shown is aspx). I'd like to do some resizing of the window based on the number of rows in a datatable that's coming back. So naturally I go to register a startup script that resizes the window based on the number of rows. Well, that didn't work, so I tried to register a script that just showed a msgbox.
The code looks like (in the OnLoad event handler):
if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
{
this.ClientScript.RegisterStartupScript(typeof(MyPageClassName), "hello",
#"<script language=vbscript>
sub fnWindowOnLoad()
MsgBox ""hello""
end sub
<script>", false);
}
if (!this.ClientScript.IsStartupScriptRegistered(typeof(MyPageClassName), "hello"))
{
throw new Exception("Failed to load script");
}
To me it looks like this should work and show a message box that says "hello" when the page loads (I've got the window's onload event set to fnWindowOnLoad). But what happens is nothing, no exception, no alert. I've tried every Type I could think of in the typeof call. Nothing seems to work. The only thing I can think of is that since the dialog is a modal ClientScript.RegisterStartupScript won't run properly. But that doesn't make any sense to me.
I put the MsgBox "hello" call into my script block directly and the alert showed, so it's possible. But I need to modify some arguments in the code behind so I have to use RegisterStartupScript as far as I can tell.
Have you tried opening your window via window.open() rather than window.showModalDialog()? I've seen some postings on the web about incompatibilities between showModalDialog() and RegisterStartupScript.
showModalDialog() is an IE only method, so it's not recommended anyway. I know it's convenient because it returns a value, but there are various ways to simulate this functionality.
Edit: The other problem with showModalDialog() is that IE often caches the results. This means that if one time you calling the dialog, you do not resize it, then another time you do, then 2nd time might get your the first cached dialog. A way to get around this is to add a unique querystring at the end. Like MyDialog.aspx?q=320934 (randomly generated or generated based on server tics).
The solution for this was to have a script that read a value out of a hidden field and then resized the dialog. The value was set on the Page_Load. Using RegisterStartupScript never seemed to work, neither did RegisterClientScript, so I'm pretty sure modal dialog and RegisterXxx don't get along. Need to use window.dialogHeight & window.dialogWidth in the vbscript.

Asp.net and JavaScript pop up windows

I am writing an intranet application and am considering the use of a pop up window. I am not worried about accessibility since it's an intranet app.
The scenario is such as I need to be able to have the same code be used in a server page as well as in the middle of a process; which is why I decided when using it in the middle of the process, it's best to have it as a pop up window to running out of the real estate on the screen.
Any thoughts on this? I am hesitant to use a pop up window in such a manner as I usually only use it for error messages.
I don't completely understand what you're trying to do, but I think a popup window might be somewhat of an issue if the user's browser automatically blocks popup windows. Plus, if you were trying to run a process in the popup window, the user could close it and no longer have a way to check on the process.
Would it be possible to use Ajax to call back to a web service that gives the page information about the process? You could give the user a way to make the Ajax call to check on the status of the process or just have it continually polling in the background.
Edit:
You said you weren't too familiar with Ajax. For the most part, there are libraries to handle all the of hard details. I'll recommend jQuery because that's what I've been using for a while now.
If you go the Ajax route you'll be able to contain everything on one page and make the updates you need to make when the Ajax call is successful. Depending on how you write the code, it should be pretty reusable if you do it right. It really depends on how specific the your needs on each page.
Take a look at the jQuery documentation though. It may have what you need already built into it. Otherwise, someone else might be able to suggest some reasons why their favorite JavaScript library works better for what you're trying to do.
I think you might want to do something like this:
Inside of the parent page:
<input id="btnShowModal" runat="server" type="button" value='Show Modal' onclick="ShowModal()" />
function ShowModal()
{
var retVal = window.showModalDialog("MyPopup.aspx?param1=value","","center=yes;dialogWidth=200px;dialogHeight=200px;status:0;help:0")
if(retVal != "" && retVal != undefined)
{
//This code will be executed when the modal popup is closed, retVal will contain the value assigned to window.returnValue
}
}
Inside of the modal popup:
<input id="btnSave" runat="server" type="button" value='Save' onclick="Save()" />
function Save()
{
window.returnValue = "Whatever you want returned to the parent here"
window.close()
}
The usual argument against popup windows is that they are unreliable. The user may have disabled script initiated popups, I know I have.
In a controlled environment, such as an inranet, you may be able to be guaranteed that this is not the case, but even so, why risk it, there is an alternative.
Instead of popping up a new window just insert a new, absolutely positioned <div> into the document and insert your content into that using ajax or even an <iframe>. There are lots of examples/libraries on the web.
Thickbox for jQuery for example. There are of course scripts that don't require libraries.
I generally use a div with a z-index and absolute positioning; the .show() can be written and called on demand, it would have a button to .close(), and AJAX can make it seem modal so it must be clicked to close if you so desire. Then again, I hate messageboxes.
I was trying to avoid AJAX, simply because I have never used and don't have the time frame to learn it now. However, I am not totally opposed to it.
In short what I need to do is for the pop up window interact back with the page. Imagine that on the page I am building the links of the chain. Each link has unique properties. When user clicks on "ADD LINK" button, I was thinking have a pop up window with the little form and a Save button. The only issue with this is that a pop up needs to interact with the page; we need to know when something has been saved or not saved.
A div on the same page is one way. A pop up is yet another way. Another catch is that this code (adding new link) needs to be reusable, because I am also going to have a page that just creates new links.

Setting Focus with ASP.NET AJAX Control Toolkit

I'm using the AutoComplete control from the ASP.NET AJAX Control Toolkit and I'm experiencing an issue where the AutoComplete does not populate when I set the focus to the assigned textbox.
I've tried setting the focus in the Page_Load, Page_PreRender, and Page_Init events and the focus is set properly but the AutoComplete does not work. If I don't set the focus, everything works fine but I'd like to set it so the users don't have that extra click.
Is there a special place I need to set the focus or something else I need to do to make this work? Thanks.
We had exactly the same problem. What we had to do is write a script at the bottom of the page that quickly blurs then refocuses to the textbox. You can have a look at the (terribly hacky) solution here: http://www.drive.com.au
The textbox id is MainSearchBox_SearchTextBox. Have a look at about line 586 & you can see where I'm wiring up all the events (I'm actually using prototype for this bit.
Basically on the focus event of the textbox I set a global var called textBoxHasFocus to true and on the blur event I set it to false. The on the load event of the page I call this script:
if (textBoxHasFocus) {
$get("MainSearchBox_SearchTextBox").blur();
$get("MainSearchBox_SearchTextBox").focus();
}
This resets the textbox. It's really dodgy, but it's the only solution I could find
this is waste , its simple
this is what you need to do
controlId.focus(); in C#
controlID.focus() in VB
place this in page load or button_click section
eg. panel1.focus(); if panel1 has model popup extender attached to it, then we put this code in page load section
How are you setting focus? I haven't tried the specific scenario you've suggested, but here's how I set focus to my controls:
Public Sub SetFocus(ByVal ctrl As Control)
Dim sb As New System.Text.StringBuilder
Dim p As Control
p = ctrl.Parent
While (Not (p.GetType() Is GetType(System.Web.UI.HtmlControls.HtmlForm)))
p = p.Parent
End While
With sb
.Append("<script language='JavaScript'>")
.Append("function SetFocus()")
.Append("{")
.Append("document.")
.Append(p.ClientID)
.Append("['")
.Append(ctrl.UniqueID)
.Append("'].focus();")
.Append("}")
.Append("window.onload = SetFocus;")
.Append("")
.Append("</script")
.Append(">")
End With
ctrl.Page.RegisterClientScriptBlock("SetFocus", sb.ToString())
End Sub
So, I'm not sure what method you're using, but if it's different than mine, give that a shot and see if you still have a problem or not.
What I normally do is register a clientside script to run the below setFocusTimeout method from my codebehind method. When this runs, it waits some small amount of time and then calls the method that actually sets focus (setFocus). It's terribly hackish, but it seems you have to go a route like this to stop AJAX from stealing your focus.
function setFocusTimeout(controlID) {
focusControlID = controlID;
setTimeout("setFocus(focusControlID)", 100);
}
function setFocus() {
document.getElementById(focusControlID).focus();
}
I found the answers from Glenn Slaven and from Kris/Alex to get me closer to a solution to my particular problem with setting focus on an ASP.NET TextBox control that had an AutoCompleteExtender attached. The document.getElementById(focusControlID).focus() kept throwing a javascript error that implied document.getElementById was returning a null object. The focusControlID variable was returning the correct runtime ClientID value for the TextBox control. But for whatever reason, the document.getElementById function didn't like it.
My solution was to throw jQuery into the mix, as I was already using it to paint the background of any control that had focus, plus forcing the Enter key to tab through the form instead of firing a postback.
My setFocus function ended up looking like this:
function setFocus(focusControlID) {
$('#' + focusControlID).blur();
$('#' + focusControlID).focus();
}
This got rid of the javascript runtime error, put focus on the desired TextBox control, and placed the cursor within the control as well. Without first blurring then focusing, the control would be highlighted as if it had focus, but the cursor would not be sitting in the control yet. The user would still have to click inside the control to begin editing, which would be an UX annoyance.
I also had to increase the timeout from 100 to 300. Your mileage my vary...
I agree with everyone that this is a hack. But from the end-user's perspective, they don't see this code. The hack for them is if they have to manually click inside the control instead of just being automatically placed inside the control already and typing the first few letters to trigger the auto lookup functionality. So, hats off to all who provided their hacks.
I hope this is helpful to someone else.

Resources