AutoComplete Stopping When User Presses "Enter" - asp.net

I am using the AutoCompleteExtender on a commercial site. My problem is the users are quickly typing in part of a word and immediately pressing "Enter" which causes the AutoComplete control to NOT come back with a list of suggestions. For example, if my database has the phrase "Texas, United States" in it but the users just type "Texas" quickly followed by Enter then the dropdown list does not appear.
What I would like is for the AutoComplete control to ignore the fact the user has pressed Enter and go and fetch the suggested data anyway. (The ultimate would be if it ignored Enter when there was currently no list, but selected an item when there was a list).
I can simulate this exact problem by going to the samples section of this Microsoft ASP.NET site and typing in some characters very quickly followed by 'Enter'.
Please could someone tell me what I need to do?
Thanks, Martin

I've hacked around this problem before with an extra keydown handler on the textbox that is the target of the auto-complete. Replace this._autoCompleteBehavior in the snippet below with a reference to your instance of AutoCompleteBehavior (obtainable via $find() and the BehaviorID). The idea here is to force the auto-complete behavior to think it needs to perform a lookup by calling _onTimerTick(), which executes after the typing delay has expired. By default the typing delay gets cancelled by hitting the enter key, so this just forces the lookup anyway on enter or tab.
Disclaimer: my hack references "private" members of the AjaxControlToolkit code (stuff that starts with underscore is "private"), so it is probably not guaranteed to be future-proof.
_searchTextbox_keydown: function(e)
{
var key = e.keyCode || e.rawEvent.keyCode;
// If the user hits enter or tab before the auto complete popup appears, force the autocomplete lookup at that moment.
if ((key === Sys.UI.Key.enter || key === Sys.UI.Key.tab) && this._autoCompleteBehavior._currentPrefix != this._autoCompleteBehavior._currentCompletionWord())
{
this._autoCompleteBehavior._onTimerTick(this._autoCompleteBehavior._timer, Sys.EventArgs.Empty);
e.preventDefault();
}
}

Hey try jQuery or YUI autocomplete extender. It will be lightning fast.

Related

SharePoint PeoplePicker - Prevent user deleting value

I have a form with a PeoplePicker control on it that I do not want the user to be able to edit.
Normally in situations like these setting the controls Enabled property to false would suffice, however I'm having issues with the value being cleared on postback (the form is very customised with numerous sub-sections that interact with each other).
I've tried the following:
peoplePicker.EnableBrowse = false;
peoplePicker.AllowTypeIn = false;
This solves nearly all my problems, the user cannot enter any values, the value is not cleared on postback, HOWEVER, the user is able to delete the current value.
How can I completely prevent the user from editing the controls value without setting Enabled to false?
Any help is greatly appreciated. Thanks.
EDIT: Forgot to mention this needs to be done server side, there's a lot of logic on the form revolving around the users AD group and their sharepoint permissions so javascript isn't really an option.
SharePoint people picker is basically a div with contenteditable property. If you can inject javascript, here is the solution:
http://www.stuartroberts.net/index.php/2012/03/05/quick-tip-5/
You could prevent users from deleting value by pressing event of Backspace and Delete keys using JavaScript/jQuery solution.
Solution
Along with specifying EnableBrowse and AllowTypeIn properties, add the following script on the page where PeopleEditor control resides:
$("body").on("keydown", "span", function(e) {
if ( (e.keyCode == 8 || e.keyCode == 46) && e.target.id.indexOf("userPicker_upLevelDiv") > -1)
e.preventDefault();
});

WebBrowser Control programming Tabs within Document pages query

I am trying to download information from a website and I have hit (yet another) brick wall in a long and tiresome journey to get something productive developed.
I have a program which uses WebBrowser to login to a site - with a valid username and password - therby allowing me to set up a legitimate connection to it and retrieve information (my own) from it.
From the initial page presented to me after login, I can use WebBrowser.Document.GetElementsByTagName("A") and WebBrowser.Document.GetElementById("Some Id") etc. to work my way around the website, and processing all the DocumentCompleted events returned until ... I arrive at a page which appears to have a TabControl embedded in it.
I need to be able to choose the middle Tab of this control, and retrieve the information it holds. When I access this information 'normally' (i.e. from IE and not from my WebBrowser program) I can click each of the three tabs and information duly appears - so its there, tantalisingly so ... but can I manupulate these Tabs from my program? I feel it should be possible, but I can't see how I can do it.
The problem manifests itself because when I am processing the page which has the Tab in it my code looks like this:
static void wb_TabPage(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
HtmlElement element;
element = wb.Document.GetElementById("Bills"); // Find the "Bills" tab
element.InvokeMember("Click"); // Click the "Bills" tab
// Unhook THIS routine from DocumentCompleted delivery
wb.DocumentCompleted -= new WebBrowserDocumentCompletedEventHandler(wb_TabPage);
// Hook up this routine - for the next 'Document Completed' delivery - which never arrives!
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_Bills);
return;
}
And that's the problem - no more Documents are ever 'Completed' for me to process, even after the InvokeMember("Click"). It seems for all the world that the Tabs are being updated inplace, and no amount of Refresh(ing) or Navigating or Event Handling will allow me to get to a place or in a position where I can get the data from them
Does anybody have any idea how I can do this? Does anybody know how to manipulate Tabs from WebBrowser? Thanks in advance if you do ...
Try using the findcontrol function on your page. You will likely need to drill into the tab control itself to find the tab page and the controls contained in it.

Prompt to save data if and when changes have been made

I am using asp.net and I need to display a prompt to the user if they have made changes to the web page, and they accidentally close down the browser.
The page could be anything from "Edit Profile" to a "Submit a Claim" etc.
How can I can display the messagebox, ensuring that it is displayed only if changes have been made (as opposed to, the user making changes, then undo-ing the changes, and shutting down the browser)
What I have done in the past is use some client side scripting which does this check during the onbeforeunload event....
var showPrompt=true;
var isDirty=false;
var hidePopup=false;
function onBeforeUnload() {
if (showPrompt) {
if (isDirty) {
if (hidePopup || confirm("Click ok to save your changes or click cancel to discard your changes.")) {
doSave();
}
}
}
showPrompt = true;
hidePopup = false;
}
ShowPrompt can be set to false when your clicking on an anchor tag which won't navigate you away from the page. For example <a onclick='showPrompt=false' href='javascript:doX()'/>
isDirty can be used to track when you need to save something. You could for example do something like $("input").onchange(function(){isDirty=true;}); To track undo's you might want to replace isDirty with a function which checks the current state from the last saved state.
HidePopup lets us force a save without confirming to the user.
That's very difficult to even touch without understanding what's on the page. If it's a few controls you capture value at page load and store them so you can later compare. If it's a complex page you'd need to do an exact comparison to the entire viewstate.
Typically you'd handle this type of situation by setting a boolean to TRUE the first time any change is made and disregard the user changing it back. If you're just trying to avoid accidential non-save of data the user should be smart enough to know they've "undone" their changes.
You can do this with javascript. See this question and either of the first two answers.

How to prevent an MFC dialog from handling the enter and escape keys and not passing it on

we have a C++ application that hosts a flex application in a MFC dialog. Everything works fine, all button pushes etc are passed directly on to flex with no problem at all, except the enter and escape keys, which immediately closes the dialog.
We can trap the enter key, by implementing PreTranslateMessage() or OnOK()
and impede the window closing behavior, but we still have the problem of passing these enter key pushes on to the hosted flex app further.
There is no "default" button on the form or anything like that, perhaps MFC is linking the enter key to the close button in the title bar behind the scenes or something.
Does anyone have any ideas how we can stop MFC from treating the enter key from being a special case.
Thanks a lot for any hints.
Edit: Here is PreTranslateMessage() that mmonem requested.
BOOL CFlexDialog::PreTranslateMessage(MSG* pMsg)
{
if ((pMsg->message == WM_KEYDOWN))
{
if (pMsg->wParam == VK_RETURN)
{
m_ctrlFlex->OnReturnKeyPressed();
return TRUE;
}
}
return __super::PreTranslateMessage(pMsg);
}
But it is not a suitable solution, calling a method in the flex app like that, as it makes life too difficult for the flex developer, it means he must write a special version implementing the return key behavior for every control.
We just want MFC to treat the return and escape keys like every other key.
Remove OnOK() and OnCancel(); PreTransateMessage is enough after considering VK_ESCAPE.
Why don't you use:
m_ctrlFlex->SendMessage(WM_KEYDOWN, VK_RETURN, 0)
instead of
m_ctrlFlex->OnReturnKeyPressed();
in your implementation of PreTranslateMessage ?
MFC command buttons can respond to events even if they do not have the focus.
Have you tried trapping the OnClicked event and OnOk to return nothing?
Example: trap OnClick...
void CMyDialog::OnClickedMyOK()
{
CDialog::OnOK();
}
Then do a no-op in the OnOk()
void CMyDialog::OnOK()
{
}
This should stop the enter key from being processed.
Another approach is "Windows Subclassing." That is, sending messages from one Window Procedure, that is a WindProc() to another WndProc(). This may provide a way without direct intervention. (This is not C++ subclassing.)
Here's a way with MFC Subclassing Edit: Provided a better link.
Search for "Windows / MFC Subclassing" if more info needed.
The flex control/window has a WndProc and your window certainly has a WndProc, Windows Subclassing should work.
New Edit: Here is perhaps a better link for subclassing an ActiveX control.
ActiveX Controls: Subclassing a Windows Control
Subclassing Windows Forms Controls - More .Net-centric.
Notice: In MFC you should see these functions.
CWnd::SubclassDlgItem
CWnd::SubclassWindow
CDialog inherits from CWnd so you will see those two functions as "dialog" functions as well. They are key to making this work. If the flash window is a true window, use SubclassWindow. If it's a control use SubclassDlgItem.
And finally, if nothing else works. A product/library that will hopefully make it easy. EasyHook looks like a product here. EasyHook at CodeProject, you can get all the source code.
If you are having issues handling tabs & enter keys I would recommend you look into using a window instead of a dialog. The dialog adds modal ( if you are using modal ), tabbing & default button handling. If you don't need/want those features, or if they are getting in your way, then don't use a dialog.
If I understand what you are doing, then you want flex to handle tabbing, enter key, and all sorts of other messages. Get the dialog code out of the way. If you still want modal style, then you may have to handle the enable/disabling of parent windows - thats all that windows does when you open a modal dialog.

ASP.NET linkbutton raising onBeforeUnload event twice

I've posted this here, but thought it might deserve a question on its own.
What I'm trying to do is show a dialog box that asks the user if he/she wants to leave the page if there are unsaved changes. That all works fine. But the problem is described below:
Has anyone come across the problem where Internet Explorer fires the onbeforeunload event twice? While Googling around, I found it has something to do with the fact that for (among others) an ASP.NET linkbutton the HTML code is <a href="javascript: __doPostBack....
Apparently, when IE encouters a link that doesn't have a href="#", it fires the onbeforeunload event. Then, when you confirm the javascript dialog box we're showing, the page will do the 'real' unload to navigate to the other page, and raise the onbeforeunload event a second time.
A solution offered on the internet is to set a boolean variable and check on it before showing the dialog. So the second time, it wouldn't be shown. That's all well, but when the user cancels, the variable will still be set. So the next time the user wants to leave the page, the dialog won't be shown anymore.
Hope this is a little clear, and I hope someone has found a way around this?
In reaction to annakata: Yes, but you want the result of the dialog box to be used by the browser. So you might think using 'return bFlag' would do the trick (or event.returnValue = bFlag), but that gives you a second dialog box.
I've found a way around, thanks to this page. It's quite simple actually:
var onBeforeUnloadFired = false;
Use this global variable here:
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You'll lose changes!";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 1000);
And then implement that function:
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
So, in effect, use the flag, but reset it if the user clicks cancel. Not entirely what I would like, but haven't found anything better.
I haven't encountered this, but surely you could set the flag variable to be equal to the result of the dialog? If the user cancels the flag will therefore remain false.
var bFlag = window.confirm('Do you want to leave this page?');
IE supports an event on the document object called onstop. This event fires after the onbeforeunload event, but before the onunload event. This isn't exactly pertinent to your two dialogs question, but its still relevant to other people that might stumble on this thread ( as I did ).
The problem I was having, was that I needed to display a loading message upon the onbeforeunload event firing. This is all fine until the page has some sort of confirm dialog on it. The onbeforeunload event fires even if the user cancel's and remains on the page. The easiest thing for me to do was to move my "loading" display logic into a handler for document.onstop. On top of this, you have to check the readyState property of the document object, which is another IE-only field. If its "loading", it means the user is actually leaving the page. If its "complete", it means the user is staying.
If you are fine with just using IE, then you might be interested in the following.
document.onstop = function()
{
try
{
if( document.readyState != "complete" )
{
showLoadingDiv();
}
}
catch( error )
{
handleError( error );
}
}

Resources