I have the following situation: I have a textbox inside an ajax updatepanel. Wherever the user types in the textbox I must display a message (different message that depends on the user typed data).
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:TextBox ID="txtMyTexbox" runat="server" Width="500px" OnTextChanged="txtMyTexbox_TextChanged" AutoPostBack="true"></asp:TextBox>
<br />
<asp:Label ID="lblMessage" runat="server" CssClass="errorMessage" Visible="false">Hello World</asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMyTexbox" />
</Triggers>
</asp:UpdatePanel>
In server side I have written the following at page load
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtMyTexbox);
and the method like this
protected void txtMyTexbox_TextChanged(object sender, EventArgs e)
{
if (.....)
{
lblMessage.Visible = false;
}
else
{
lblMessage.Visible = true;
}
}
My problem now is that: when the user types in the textbox it doesn't cause OnTextChanged event.
Am I missing something?
I'm not sure that your problem has anything to do with the UpdatePanel.
In fact, the TextChanged event doesn't fire while typing. It will only fire after the textbox loses focus. This happens directly if AutoPostBack is set to True, or when the next postback occurs. Please see the docs for the AutoPostBack property and the TextChanged event.
Afaik, your best bet is probably to handle the keyup event in javascript.
Here's a simple jQuery example:
$(document).ready(function() {
$(':text[id$=YourTextBox]').keyup(function() {
if ($(this).val() === "your special value") {
$('span[id$=YourLabel]').css('visibility', 'visible');
}
else {
$('span[id$=YourLabel]').css('visibility', 'hidden');
}
});
});
Set the EventName property for your txtMyTexbox AsyncPostBackTrigger to TextChanged
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtMyTexbox" EventName="TextChanged" />
</Triggers>
Other sugguestion:
Have you tried looking at the AutoComplete control that is part of the AjaxControlToolKit? Its behaves the same way you want your solution to behave.
its strnage to know that even after adding update panel / AsyncPostBackTrigger , TextBox ChangeEvent doesn't work properly. Some time its works and some times it not..Since its is Asychronous call, we need to some time refresh, or wait or unpredictable , Hopes microsoft will come up with competent one.. Below are easy way to check user name pretty good
------ Under Page_Load - aspx.cs -----------------------
this.TextBox1.Attributes.Add("onKeyUp", "fnUNameSubmit(this);");
-------in aspx -add script ---------------------------------------
<script language="javascript" type="text/javascript">
function fnUNameSubmit(urInput) {
var inpt= urInput.value;
if (inpt.length > 21) {
document.getElementById('<%= TextBox1.ClientID %>').style.backgroundColor = "green";
document.form1.submit(); // This is only trick we use here..
}
else {
document.getElementById('<%= TextBox1.ClientID %>').style.backgroundColor = "red";
}
}
</script>
-------in aspx -add script ---------------------------------------
----------------aspx.cs -------------------
if (TextBox1.Text.Length > 21)
{
CheckUsrName();
Label2.Text = "";
}
else
{
Label2.Text = "Length is less than 21"; //lets do some stuff..bla..bla
}
------------------------------------------------- CheckUsername()
public void CheckUsrName()
{
Call dB values
}
You should not be using RegisterAsyncPostBackControl for your TextBox. That method is really only for use for controls that reside outside of UpdatePanels. I would try removing that line of code and seeing what happens.
See this for more info: http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerasyncpostbackcontrol.aspx
a workaround check textbox - causesvalidation property and set it to true
The Control which id is used in AsyncPostBackTrigger must be outside the update Panel(that cause to fire the Async call) like this:
<tr>
<td colspan="4"><asp:Label ID="lblEnter_Successfully" Text="Enter Record SuccessFully" runat="server" Visible ="false" ForeColor ="Blue" Font-Size ="Larger" Font-Bold ="true"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "Button_Save" EventName ="Click"/>
</Triggers>
</asp:UpdatePanel>
<table>
<tr>
<td width = "472px" align ="right">
<asp:Button ID="Button_Save" runat="server" Text="Save" OnClientClick ="return URLValidation();"/>
<asp:Button ID="Button_Clear" runat="server" Text="Clear"/>
</td>
</tr>
</table>
Related
I am doing a project in asp.net. i have a panel which contains some field like txtbox ,buttons etc..I want to use jquery event on a asp.net button click which will open this panel by using jquery show() function and also perform some tasks in server side. Please help me.
The code is :
protected void btninsertfordeo_Click(object sender, EventArgs e)
{
// GridViewforcontact.Enabled = false;
PanelForInsert.Visible = true;
colvisible = true;
txtfaxnoextra.Focus();
if (colvisible == true)
{
GridViewforcontact.Columns[9].Visible = false;
}
colvisible = false;
}
You can use the OnClientClick property of the button to call your client-side function and OnClick to call your server code
<asp:Button ID="btninsertfordeo" runat="server" OnClientClick="functionToShowPanel()" OnClick="hlkContinue_Click" Text="Click"></asp:Button>
<script>
functionToShowPanel(){
$('#pnlToShow').show()
}
</script>
or without using OnClientClient you can probably do:
$('#<%=btninsertfordeo.ClientID %>').click(function(){
$('#pnlToShow').show()
}
Another option would be to use an UpdatePanel instead of jquery to show/hide elements on the page. This way you can control the visibility of your div from your code-behind. Add all the dynamic elements within the UpdatePanel's ContentTemplate and add your button as an AsynPostbackTrigger for the UpdatePanel to enable dynamic updating of our page.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btninsertfordeo" EventName="click" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="PanelForInsert" runat="server" Visible="false">
//Your textboxes, buttons etc goes here
</asp:Panel>
<asp:Button ID="btninsertfordeo" runat="server" Text="Click" OnClick="btninsertfordeo_Click"></asp:Button>
</ContentTemplate>
</asp:UpdatePanel>
Here are links to documentation that will help you in understanding and implementing an UpdatePanel:
Introduction to the UpdatePanel
UpdatePanel Control Overview
UpdatePanel Class
<script type="text/javascript">
function ClientSideClick(myButton) {
//make sure the button is not of type "submit" but "button"
if (myButton.getAttribute('type') == 'button') {
// disable the button
myButton.disabled = true;
//myButton.className = "btn-inactive";
myButton.value = "Posting...";
}
return true;
}
</script>
<asp:UpdatePanel ID="upComments" runat="server" UpdateMode="Always" >
<ContentTemplate>
<asp:ListView ... >
<asp:Button ID="btnSubPostComment" runat="server" Text="Reply Comment"
CommandName="cmdPostSubComment" OnClientClick="ClientSideClick(this)" UseSubmitBehavior="false"
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
The Javascript function (ClientSideClick) disables the button when it's processing.
The problem is that when I include
OnClientClick="ClientSideClick" UseSubmitBehavior="false"
in my button, even though it's inside an Update Panel it causes full postback.
If I remove those two Properties OnClientClic and UseSubmitBehavior the button does not cause full postback. Does anyone know why this happens?
All I wanted to do is disable the button and chagne it's text to prevent multiple submissions.
I'm not sure if this is exactly what you're looking for but I usually use this:
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<script type="text/javascript">
var pbControl = null;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
pbControl = args.get_postBackElement();
pbControl.disabled = true;
}
function EndRequestHandler(sender, args) {
pbControl.disabled = false;
pbControl = null;
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<asp:ListView ... >
<asp:Button ID="btnSubPostComment" runat="server" Text="Reply Comment" CommandName="cmdPostSubComment" OnClientClick="this.value='Posting...';" />
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
The only problem is that if the same button is clicked again after the first async postback then it throws a "Operation is not valid due to the current state of the object" error. This might appear as a javascript exception in the form of a 500 internal server error. After doing some research, I came across:
"Microsoft recently (12-29-2011) released an update to address several serious security vulnerabilities in the .NET Framework. MS11-100 was introduced just recently that handles potential DoS attacks. Unfortunately the fix has also broken page POSTs with very large amounts of posted data (form fields). MS11-100 places a limit of 500 on postback items. The new default max introduced by the recent security update is 1000."
Scott Gu writes about it here: http://weblogs.asp.net/scottgu/archive/2011/12/28/asp-net-security-update-shipping-thursday-dec-29th.aspx
Adding the setting key to the web-config file overcomes this error:
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2000" />
</appSettings>
I have an asp.net form which contains a dropdownlist which posts back to the server on change and populates second dropdownlist with some dates.
The form also contains other fields some of which are validated clientside and some server side.
Here's the problem I'm having. If I get a clientside validation error then try to change the dropdownlist, the second dropdown does not get populated. If I then change the first dropdownlist again, it works as expected.
Here's my submit button:
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClientClick="Page_ClientValidate(); return checkPassengers();" OnClick="Page_Transfer" ValidationGroup="FormSubmit" />
Here's my clientside validation:
function checkPassengers() {
if($("#testField").val() == "Name *" || $("#testField").val() == "") {
$("#pltester").prepend("<p class='fillall'>Please fill in all fields marked with *</p>");
return false;
}
};
Dropdowns:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl1st" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:DropDownList ID="ddl1st" Width="190" AutoPostBack="true" OnSelectedIndexChanged="ChooseDates1st" runat="server" />
<asp:DropDownList ID="ddlDepart1st" AutoPostBack="true" runat="server" />
</ContentTemplate>
</asp:UpdatePanel>
I've ran into this problem many times before when using updatepanels.
I've found that if the field needs to be validated then you have to actually set CausesValidation="true" on the element for it to still work with updatepanels.
Hope this helps you out!
Simply setting CausesValidation="true" did not resolve the issue for me. This appears to be issue when using asp dropdownlist's SelectedIndexChange event.
The workaround I found was to reset the validation on front end with a js by validating non-existing validation group name before the postback.
function ignoreValidation() {
if (typeof Page_ClientValidate != 'undefined') {
Page_ClientValidate('reset-validation');
Page_BlockSubmit = false;
}
return true;
}
And for dropdownlist
<asp:DropDownList CausesValidation="false" onchange="ignoreValidation();" runat="server" ID="CustomerDropDownList" OnSelectedIndexChanged="LoadCustomers" AutoPostBack="true"/>
If the Drop-Down list doesn't need to be validated, you can set CausesValidation="false" on the initial dropdown list. This will cause it not to trigger validation, so it can be changed at will.
Alternatively, you could put the DropDownList in a different ValidationGroup so that changing it doesn't trigger validation on the other controls.
function validateCommand(group) {
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate(group);
if (Page_IsValid) {
Page_BlockSubmit = !confirm('Are you sure?');
}
}
}
I have an ASP.Net UpdatePanel that updates on a timer. Within the UpdatePanel and nested in a GridView, I have a TextBox that the user enters a value in with a submit button. Everything works fine, except if the user does not submit the value before the timed interval, the text is removed from the TextBox.
Is there a way to persist the user entry into the TextBox between updates? Is there a better way of doing this?
All suggestions welcome.
Respectfully,
Ray K. Ragan
Code Postscript:
aspx:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beginRequest);
function beginRequest() {
prm._scrollPosition = null;
}
</script>
<asp:Timer ID="Timer1" runat="server" Interval="900" OnTick="Timer1_Tick"></asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:DataList RepeatColumns="5" RepeatDirection="Horizontal" ID="dlMine" runat="server" OnItemCommand="Item_Command">
<ItemTemplate>
<div style="border:1px solid black;margin:3px;height:300px;text-align:center;padding:5px;">
<div style="width:150px;">
<asp:Label ID="lblTitle" runat="server" Text='<%# left(DataBinder.Eval(Container.DataItem,"title").ToString(), 75) %>'></asp:Label>
</div>
<asp:Label ID="Label1" runat="server" Text='<%# (DateTime)DataBinder.Eval(Container.DataItem,"end_date") %>'></asp:Label>
<br />
<asp:Label ID="Label2" runat="server" Text='<%# String.Format("{0:C}",DataBinder.Eval(Container.DataItem,"current_value")) %>'></asp:Label>
<br />
<asp:TextBox ID="txtNewValue" runat="server"></asp:TextBox>
<asp:Button Visible='<%# (isInThePast((DateTime)DataBinder.Eval(Container.DataItem,"end_date"))) ? false : true %>' CssClass="bid_button" runat="server" CommandArgument='<%# Eval("ID") %>' CommandName="Revalue" ID="btnBid" Text="Submit New Valuation" />
</div>
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
Timer1.Tick += new EventHandler<EventArgs>(Timer1_Tick);
if (!IsPostBack)
{
dataBindList();
}
}
protected void dataBindList()
{
if (Request.QueryString["GroupID"] != null)//Are they coming here with a URL var? If so, build content object
{
List<Item> itemList = ItemManager.getItemsByGroupID(Request.QueryString["GroupID"].ToString());
dlMine.DataSource = itemList.Take(15);
dlMine.DataBind();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
dataBindList();
UpdatePanel1.Update();
}
protected void Item_Command(Object sender, DataListCommandEventArgs e)
{
if (e.CommandName == "Revalue")
{
Person p = (Person)Session["Person"];
foreach (DataListItem item in dlMine.Items)
{
string textBoxText = ((TextBox)item.FindControl("txtNewValue")).Text;
Utilities.writeLog("txtNewValue: " + textBoxText, 1);
}
dataBindList();
UpdatePanel1.Update();
}
}
You're rebinding the DataList every time the Timer ticks. All changes in the ItemTemplates of the DataList will be lost on postback.
Why not use Javascript to "pause" the timer whenver one of the textboxes gains focus. This will prevent the Timer from firing and let users finish entering text. Once they leave the textbox of "onblur" then you can restart the timer.
Update
The following will take a bit of effort to make it happen but you can do something like:
When the Timer posts back, before rebinding, iterate over the DataList while searching for textboxes with text in them. Something like:
foreach (DataListItem item in dlMine.Items)
{
//find the textbox control and check for text
}
At this point, you'll know which rows need there textboxes repopulated. Store this information in a hashtable.
In the DataList ItemDataBound event, check each rowID against the hashtable to see if its corresponding textbox exists. If so, repopulate the textbox in the DataList row.
Are you initializing the TextBbox value in your code-behind, perhaps in Page_Load or another page method?
TextBox1.Text = "";
If so, that code is executing on every timer event. You can prevent that like this:
if (! IsPostback) {
TextBox1.Text = "";
}
The first request that hits an ASP.NET page is usually an HTTP GET request, while ASP.NET buttons and update panel events issue HTTP POST requests. So the code above will clear TextBox1 the first time you access the page, but leave the value alone when receiving requests from itself. (If you really are setting the text box's value to its default - empty - you could just remove the initialization code.)
I have an ASP page with an asp:DropDownList (with AutoPostBack="true") so that when the user changes it, it reload the appropriate data.
Under that control i have a list of UserControls, that includes a tinymce editor (tied to an asp:TextBox) and an asp:ImageButton to save the data.
When clicking on the ImageButton, the applications send the postback data via ajax to the same page (__EVENTARGUMENT, __EVENTTARGET, etc...). Why does it load that ajax page, and how do i prevent it? I'm updating the value in the DB in the OnClick event handler on the ImageButton, so all I need to do, is get ride of that ajax call.
Any ideas?
Solution 1
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="return false;" />
OR
Solution 2
<asp:ImageButton ID="btn" runat="server" ImageUrl="~/images/yourimage.jpg"
OnClientClick="yourmethod(); return false;" />
In addition (solution 2), your javascript method may be in this form
<script type="text/javascript">
function yourmethod() {
__doPostBack (__EVENTTARGET,__EVENTARGUMENT); //for example __doPostBack ('idValue',3);
}
</script>
in code behind
protected void Page_Load(object sender, System.EventArgs e)
{
if (this.IsPostBack) {
string eventTarget = this.Request("__EVENTTARGET") == null ? string.Empty : this.Request("__EVENTTARGET");
string eventArgument = this.Request("__EVENTARGUMENT") == null ? string.Empty : this.Request("__EVENTARGUMENT");
}
}
You've not stated you're using an UpdatePanel but this is presumably how you've implemented ajax calls. If so you need to add a trigger to exclude the imagebutton event from ajax:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="ImageButton" />
</Triggers>
<ContentTemplate> </ContentTemplate>
</asp:UpdatePanel>