LinkButton not firing PostBack with image and ImageMap associated with it - asp.net

I'm having one hell of a time trying to figure out why I can't get the LinkButton to PostBack when I have an image with an ImageMap associated with it.
Let me describe the system a little, so you can get a basic understanding of what's happening. The LinkButton has onClick set to call window.shoModalDialog, which obviously opens a modal window where the user can select various options an an ImageMap, save, and close the window. When the window closes, a PostBack is supposed to occur so that the main landing page gets updated with the new options selected.
To add complexity, the link button needs to have an image that shows what points were selected in modal window (the image is a smaller version of the previous window). So what I've done is add an image map to the image in the LinkButton like so:
<asp:Panel ID="pnlC2R1" runat="server">
<asp:LinkButton ID="HyperLink1" runat="server">
<img ID="SomeImage" alt="Some image"
runat="server" src="~/Images/SomeImage.jpg" usemap="#SomeMap" />
</asp:LinkButton>
</asp:Panel>
The map is a regular HTML map (not the ASP.NET one, though I'm sure it's rendered the same, but I digress). Also, I'm using ImageMapster to highlight the points that have been selected, but that doesn't cause any issues as far as I can tell.
If I remove the usemap attribute, a PostBack occurs, if I add it back in, it doesn't.
Is the ImageMap overriding the events that are supposed to occur under normal conditions for the LinkButton? Is there a way to make the ImageMap do a PostBack like the `LinkButton' would under normal circustances?
I tried using the ASP.NET ImageButton control, but I couldn't figure out how to get the ImageMap on it, if that's even possible.
Any help would be greatly appreciated, and please let me know if I need to clarify anything, I'm fairly certain half of what I wrote probably doesn't make sense. :D
UPDATE
The issue had nothing to do with the ImageMap itself. It had to do with the OnClientClick closing the modal dialog before the OnClick event could be called.

Use the asp:ImageMap instead
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.imagemap.aspx

Related

How to prevent validation for an event handler of a user control?

I have a user control with a delete button. When a button is clicked, an event fires which deletes a record from the database. Now, the control is placed in Default.aspx. The whole body markup of Default.aspx (including the user control with its button itself) resides in <form runat="server"> as required by ASP.NET. Everything works so far.
However, the problem is when I put some validation controls inside Default.aspx (meaning inside <form runat="server"> because otherwise the page will report server errors). When validation controls are added, the delete button in the user control stops working. Clicking on this button no longer triggers the event as before.
Now, I disabled event validation in Default.aspx using EnableEventValidation="false" directive. I am also including UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None; in the code behind file. However, none of this helps.
How do I fix this problem and make the button clickable?
Update:
I know for sure that the validation controls are causing the problem, because I only need to add EnableClientScript="False" to each of them, and the button becomes clickable. But I don't want to rewrite validation on the client side manually!
It turns out the PostBack cannot occur if the form is not IsValid regardless of what element causes it. As long as that element (button) is inside the form with runat="server"that is invalid, the posback will not happen.
A very simple workaround is to just make the Button in my user control bypass validation: CausesValidation="False" (thanks to this question).
Another solution and maybe a more efficient one, is to use ValidationGroup. This way, all TextBoxes together with the Submit Button will belong to one group, and those controls that do not belong to that group will NOT be validated. In fact, they might have their own ValidationGroup; this will avoid interference between different controls within one Web Form.

How to never refresh UpdatePanel on post back?

I would like to embed a ListBox into an UpdatePanel. The ListBox needs to have multi select enabled, with a post back triggered on item selection. My problem is the scroll bar on postback. It gets back to the top everytime an item is clicked. I have tried different ways to back up the scroll position, there is just always something wrong with it (at least in IE8, the browser I have to focus on). Either I get a flicker, or as soon as the user uses his mouse wheel after post back, the scroll bar will then jump back to the top. This does not happen in Chrome and Mozilla.
I was thinking, maybe there is something that should work - posting back without ever redrawing my ListBox / udpating the containing UpdatePanel ? Is this possible ?
Any full postback will necessarily repaint a list view so maintaining the scroll position of the listview is going to be problematic
Smart Nav
If it is the position of the page scroll position you are struggling with then you could try smart navigation
http://msdn.microsoft.com/en-us/library/system.web.ui.page.maintainscrollpositiononpostback.aspx
I don't think browser coverage is going to be hugely reliable for this (for example see http://forums.asp.net/p/1094179/1651390.aspx)
Update Panels and postback controls
If you are just updating the content in the update panel then it shouldn't lose it's page position. Make sure you are doing the partial post back and not the full. The listbox and the control triggering the postback should both be within the update panel.
There are caveats to this though - if you have a button outside of the update panel it can trigger the partial postback if it is in the triggers collection of the panel (http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.triggers.aspx)
JQuery AJAX
The nuclear option would be to use JQuery AJAX or similar e.g. proper AJAX not the strange fake halfway house stuff that the update panels use (not to say that they aren't very useful - just need to be used judiciously). JQuery AJAX is a swine to get working within the postback architecture so I wouldn't necessarily recommend.
Maintaining the ListBox scroll position
Note - if it is the listbox scroll position that you are concerned about them this question
Maintain scroll position in listboxes in updatepanels, NOT the page
gives some good advice
Hope that helps some
I think flickers could always happen whatever you do (flickering is actually the browser that renders contents in several phases).
You should start by trying the MaintainScrollPositionOnPostBack page's property.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.maintainscrollpositiononpostback.aspx
Why do you need to postback on every item selection ? Don't you mean an async postback ?
I had a similar issue with a ListBox inside a user control, and who in turn was in an UpdatePanel. I used jQuery to deal with click events on two buttons that were selecting and unselecting all items in the listbox.
Try this:
Create a .js file (e.g. select.js) and insert your jQuery code in there. Something like:
function pageLoad() {
//insert code here
}
Important to use pageLoad() instead of (document).ready.
Then, insert the script reference in your ScriptManager:
<asp:ScriptManager ID="sm" runat="server" EnablePartialRendering="True">
<Scripts>
<asp:ScriptReference Path="~/Scripts/Select.js" />
</Scripts>
</asp:ScriptManager>

Need an asp.net control to click the button in another asp.net control

First time I have used the site. I appreciate the help I have gotten from the users before and hope to contribute as well as ask. Now, for the question.
I am developing a static toolbar that rests on the bottom on the webpage. The purpose is to display a couple of values to a user purchasing something and for the toolbar to update the information to reflect the choices. There is currently a box on the page that does this, but it rests at the top and the user would have to continuously scroll to see options appear, price changes, etc.
The values update just fine with the price in that box when certain check box buttons are clicked that auto-refresh the page (due to these check boxes changing pieces of the code). However, some things that can effect the price require a button on the page that 'recalculates' to be clicked. The information on this page is put on the page with a controller. The toolbar I am creating is a separate control.
What I am trying to do is have a button within the toolbar that will mimic the actions of the purchase button that recalculates. I tried doing this:
Code on control page for toolbar:
<input type="button" id="buttonID" class="buttonClass" runat="server" onclick="__doPostBack('<%= btnIDOtherControl.ClientID %>','OnClick');" value="Recalculate" />
Code on control with the purchase info:
<asp:ImageButton ID="btnIdOtherControl" runat="server" ImageUrl="~/image.jpg"
AlternateText="Recalculate" OnClick="recalcFunction_Click" />
That is just the current iteration. Before I did not have the 'OnClick' piece of the __doPostBack, I had ''. I also tried using a bit of jQuery. There are quite a few questions about firing an ASP.net button from javascript, but none seemed to work.
What happens is I have gotten it to a point where clicking the recalculate button in the toolbar actually DOES refresh the page, but none of the values change. If I click the recalculate button from the purchase page (where it exists normally), the value in the toolbar does not change even though the values on the page do. If I hit the recalculate button from the toolbar AFTER recalculating from the main page, the toolbar values reflect the regular values. Any other normal use of the page (such as the checkbox that auto-refreshes) will change the values correctly in both places.
If more info is needed just let me know.
Appreciate the help ahead of time!
This has to be done by using javascript or jQuery.
Use the code below:
$("#buttonID").click(function(){
$("#btnIdOtherControl").click();
});
This will trigger the button on other control to be triggered.
PS: Make sure that the ids are correct once the page is rendered in html as visual studio will append the ids of the button in the control to be (id of the control)_(actual id of the button) i.e. If on your page you have referenced control as
<user:control id="control" runat="server">
The id of your button (buttonID) on html will be control_buttonID, so you will need to use that (control_buttonID) in jQuery.
So your code will be
$("#control_buttonID").click(function(){
$("#control1_btnIdOtherControl").click();
});
On you other control make a public property with set only and call your button's click event in it, Then on your working control you have to call only that public property of other control. it should be like this :
public void PublicPropertyCallingEvent
{
set
{
Button1_ClickEvent(null,null);
}
}
You have to access this property only wherever you need.

modalpopupextender and commas appearing in my textbox asp.net

Some weird stuff is happening, I am converting an application that used to use javascript to open another web page in a tiny window for data input to use a ModalPopupExtender.
It seems to work fine, but in the OK event, when I do txtData.Text (the textbox in my modal popup), it comes back with a comma before the data, so if you type "Rabbit", it comes back as ",Rabbit".
Also when I use it multiple times, in another place where I might click to show it, and type "Fish", it starts coming back with stuff like ",Rabbit,,Fish"
I don't know why or how to stop it from doing this... any ideas?
Same here. No clue for why it happens. Every postback initiated by buttons within the panel adds commas and previous values to all text fields.
Hooking into TextBox.Text setter revealed that the corrupted data comes from postdata collection. So it means that just before postback the ModalPopupExtender corrupts the data.
P.S. I'm not using UpdatePanel, but regular Panel so there are no triggers associated with buttons.
Updated: Solution found.
The problem seems to go away when rolling back to May's release of AjaxToolKit (http://ajaxcontroltoolkit.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=27326).
Just sharing this solution to everyone on this problem. Try not to use asp control instead use html.
*<input type="text" id="txtID" runat="server" class="myClass" />*
this works fine for me.
Thanks,
I also found a forum indicating that it may be standard html behaviour for when there are multiple controls on the form with the same name. This in mind (and assuming there is a bug in the ajax controls) The way I coded around it was to add in my Page_Load the following kind of statement for each of my textboxes.
string[] vals = txtValue.Text.Split(Convert.ToChar(","));
txtValue.Text = vals[vals.Length - 1];//It appears my latest value was always in the last item
Since the form load happens before the button event I sort out my fields before they get to the event that deals with their values.
I had a similar problem, having a jQuery Dialog inside an UpdatePanel. As I could read on different sites, the problem is caused by duplicates inside the DOM tree.
In the end I found a very simple solution. I assign the dialog to the div, then open or close it by JavaScript and then run this little peace of code to remove the duplicates:
var count = $(".dialog").length;
for (i = 1; i < count; i++) {
$(".dialog").first().remove();
}
EDIT: it turned out not to be SO simple. In the end, my code looked like this:
In document ready (and also asynchronous page calls):
function AddDialog() {
var dlg = $(".dialog").dialog({ autoOpen: false });
dlg.parent().appendTo($("form:first"));
var targetSelector = ".myDialog"; // watch out: can't use ID here!
if (mustOpenDialog) {
$(targetSelector).last().remove(); //-- remove last copy
var dlg = $(targetSelector).dialog({ autoOpen: true });
var count = $(targetSelector).length;
for (i = 1; i < count; i++) {
$(targetSelector).last().remove();
}
}
if (mustCloseDialog) {
$(targetSelector).dialog("close");
var count = $(targetSelector).length;
for (i = 1; i < count; i++) {
$(targetSelector).first().remove();
}
}
}
In my complete code, mustOpenDialog and mustCloseDialog are set in codebehind.
I had the same problem with previous values coming back comma separated. It seemed that my ok button was inside the update panel and I had it in the triggers section aswell. Removing the button from the triggers section of the updatepanel solved the problem.
best regards - Tobias
My answer was similar to Smarty's. My page looked like this...
<UpdatePanel>
<GridView>
<Button> <-- These buttons fire modal popup programmatically.
<Button>
<Button>
</GridView>
<ModalPopup>
<HiddenField> <-- Dummy target of modal popup.
</UpdatePanel>
The fix was to change it to this...
<UpdatePanel>
<GridView>
<Button> <-- These buttons fire modal popup programmatically.
<Button>
<Button>
</GridView>
</UpdatePanel>
<ModalPopup>
<HiddenField> <-- Dummy target of modal popup.
I had to register each button as a postback control with the scriptmanager on the gridview rowdatabound event. The down side is that I have more full postbacks. But, it solved the problem.
This is pretty late reply, but I am documenting it here so that other may benefit.
My Scenario
Open user control inside jquery dialog on button click. This user control had update panel inside it and few textboxes. First time open the dialog, it worked like charm. On subsequent clicks to open the dialog, I noticed a weird behavior. I had few textboxes inside the user control(inside update panel). On any partial post back, the text of textboxes changed to current text, current text. If the value of textbox was fish, then upon any partial postbacks its changed to fish, fish.
The reason for this was I was using jquery to open the dialog. I also appended the dialog to form upon the click of the button.
dlg.parent().appendTo($('form:first'));
So on subsequent clicks multiple user controls where appended to DOM and hence while building the post back data, there existed more than one control with same id and hence there values where appended using "," - comma.
So my solution was simple, while closing the dialog, I just removed it from DOM
I got hint from following link. Posting it here for future reference
here
For some reason it doesn't seem to happen if the textbox is set to ReadOnly.
I'm thinking there could be a workaround by displaying an editable textbox to the user, catching the keystrokes to it, and updating a readonly textbox that is hidden from the user.
Still a bit messy, but I can't roll back to May's release because there's another bug in that release with the ComboBox that I need to avoid!
UPDATE:
As a bit of background, I have a user control (ascx) inside my modal popup because I need to reuse it. The ascx has to handle the user's input itself (the containing page doesn't know what's going on inside the control) so when the user clicks a button I do a callback and process the data. If a successful result is returned to the client callback function then I simulate a click of what the containing page thinks is the "OK" button which is actually invisible to the user.
I've changed my code to add a hidden, readonly textbox and copy the text from the original textbox into the new one every time the text changes.
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
becomes
<asp:TextBox runat="server" ID="txtName" onchange="document.getElementById(this.id + 'RO').value = this.value"></asp:TextBox>
<asp:TextBox runat="server" ID="txtNameRO" ReadOnly="true" style="display:none;"></asp:TextBox>
then when passing values back in the callback instead of getting the value of txtName, I use txtNameRO.
I don't think this will help if you're doing a postback, but you could add a callback before the postback like I have. Hopefully this will help someone anyway!
I had this issue and lost quite a bit of time on it and found that it was caused by an extra tag hiding out that I forgot to remove when changing markup.
Make sure on the .aspx page all tags line up correctly.
<div>
**Lots of code here**
</div> <-- That guy owes me a vacation!
</div>
I have successfully implemented a complete hack based on Jen's response. I use an asp:HiddenField to hold the value I want to post back, and I populate it with a pure HTML input box
<asp:HiddenField ID="txt" runat="server"/>
<input type="text" onchange='document.getElementById("<%= txt.ClientID %>").value = this.value;' />
This is lighter weight than Jen's solution as you're still only posting back one server control.
BTW, this is a very significant bug in the Ajax Toolkit. You can vote and comment on it here:
CodePlex Issue
Pretend you're in Chicago. Vote early, vote often.
For me the solution was to get the modal poup out of the main update panel. Once I did that the commas went away. If you truely need an update panel inside of the modal popup, create one of it's own inside that panel.
I did not need to roll back to previous version of the toolkit.
I have been trying to solve this for a day now and some very helpful person in my office has come up with a terrific solution!
We moved the ModalPopUpExtender and subsequent pop up panel controlled by the extender to ouside of the outermost UpdatePanel on the page, created a fake button and gave the ID of the fake button to the TargetControlID property of the ModalPopUpExtender.
<asp:Button runat="server" ID="dummyButton" CausesValidation="false" Style="display: none" />
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="dummyButton" CancelControlID="CancelPopUp" PopupControlID="PanelID" BackgroundCssClass="modalBackground" />
Inside my forms/page where the PopUp extender and panels used to be, I created an OnClick event on the button that we used to use to trigger the ModalPopUpExtender.
<asp:ImageButton ID="ButtonID" runat="server" Text="Add" ImageUrl="~/Images/Add-32-1-small.png" OnClick="LoadPopUp" />
On my button that triggers the ModalPopUpExtender, I have created an OnClick event called "LoadPopUp" - in LoadPopUp in the code behind I simply put ModalPopUpExtender1.Show();
protected void LoadPopUp(object sender, EventArgs e)
{
ModalPopupExtender1.Show();
}
I had the same problem except I am not using the AjaxControlToolkit or update panels. My problem was solved by moving the <form> tag from the ASP.net master page to the page where the textboxes are. May help someone.
has same problem and i found the solution here: http://ajaxcontroltoolkit.codeplex.com/workitem/26259
The problem is ajax last version, just INSTALL year 2009 ajax version and modalpopup will work fine with your actual code.
Tuve el mismo problema y encontré la solución en el link que indico arriba.
El problema viene con las versiones recientes de ajax, simplemente instala la version del año 2009 y el modalpopup funcionará bien con tu código actual.
The solution is to get the modal popup out of the main update panel. Once Do that the commas will go away. If you truly need an update panel inside of the modal popup, create one of it's own inside that panel.

ASP.NET default button

I have a master page with a search box and button at the top. This search functionality is taking over the "enter" key for all my web forms that use this master page. That is, if I have a login page that uses this master page and the user enters in their username/password and hits "enter", instead of logging in the user the system performs a search.
What's the best way to set up the default submit buttons. I could wrap everything in asp Panels and set the DefaultButton property, but that seems a bit tedious. Is there a better way?
use defaultbutton property of form or panel
<form defaultbutton=“button1” runat=“server”>
<asp:button id=“button1” text=“Same Page” runat=“server”/>
<asp:panel defaultbutton=“button2” runat=“server”>
<asp:textbox id=“foo” runat=“server”/>
<asp:button id=“button2” runat=“server”/>
</asp:panel>
</form>
As you have discovered default buttons can cause issues when there is more than one button on a page. I would take the Geeks suggestion but simplify it by removing the setfocus client script and extend it by adding the keydown event to both the search textbox and the login textboxes such that the enter key fires the correct button depending on if your user is using the search box or the log in box, or any other textbox you want to add the javascript to.
You can set focus on loading the page (in code behind if you like) to save the user some mouse work or tabbing if there is a sensible control for the user to start at, but otherwise the control the user is interacting with should determine the flow of the page and what the enter key does.
set focus on the text box ,
Page.RegisterStartupScript("SetFocus", "< script >document.getElementById('" + TextBox1.ClientID + "').focus();< /script >");
and then
In the keydown event for the last textbox you can do something like this:
If e.KeyCode = Keys.Enter Then
Me.Button1.Select()
End If
Rather than using javascript to manipulate the page you could put the search box and the submit button into an IFRAME on the master page. If the focus is in the iframe clicking will submit the search form, if the user is on your main form within the page they will submit the normal page.
The <iframe> src attribute points to a little self contained aspx page holding your text box and submit button which redirects to your search results form.
This is what we tried on our project which seemed to work. I changed the Search asp:Button to be an asp:LinkButton. I then added some CSS style to give it a background image to make it look like a button. LinkButtons are apparently not used by the page for determining which Button is the default action when pressing Enter. The sweet part was that LinkButton can still have click actions associated with them so I didn't have to change any of my code-behind stuff.

Resources