Refresh Control without Updater Panel using ASP.NET AJAX - asp.net

This question is directly related to my previous question ASP.NET AJAX
Is it possible to perform the post back asynchronously? I have multiple CustomTextbox controls on the page, when i post back i want to update another control on the form.
If i place all the controls in an updater panel after the first post back to a process that takes a couple of seconds to complete, any changes i have made to other contols rendered with their original values.
Any idea how to fix this?
Type.registerNamespace('Demo');
Demo.CustomTextBox = function(element) {
Demo.CustomTextBox.initializeBase(this, [element]);
}
Demo.CustomTextBox.prototype = {
initialize: function() {
Demo.CustomTextBox.callBaseMethod(this, 'initialize');
this._onblurHandler = Function.createDelegate(this, this._onBlur);
$addHandlers(this.get_element(),
{
'blur': this._onBlur
},
this);
},
dispose: function() {
$clearHandlers(this.get_element());
Demo.CustomTextBox.callBaseMethod(this, 'dispose');
},
_onBlur: function(e) {
if (this.get_element() && !this.get_element().disabled) {
/* Cridit to AdamB for this line of code */
__doPostBack(this.get_element().id, 0);
}
}
}
Demo.CustomTextBox.registerClass('Demo.CustomTextBox', Sys.UI.Control);
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

Only put the update panel around the control that needs to be updated, and make the controls that trigger the changes triggers on that update panel:
<asp:TextBox runat="server" ID="Entry2" />
<asp:TextBox runat="server" ID="Entry1" />
<asp:UpdatePanel>
<ContentTemplate>
<asp:TextBox runat="server" ID="Result" ReadOnly="true" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Entry1" />
<asp:AsyncPostBackTrigger ControlID="Entry2" />
</Triggers>
</asp:UpdatePanel>
As a result, when the postback finishes, only the stuff inside the update panel changes. AJAX posts back the values of all the controls on the page, not just the ones in the content template.
Option 2 (and more involved) would be to write a web service that does the calculation and some javascript to call it.

Related

how to use jquery on asp.net button and by using that i want to perform show() on apanel..and perform some server side code

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

ASP.NET: Button inside a ListView inside an Update Panel causes full Postback

<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>

ASP.NET DataPager Next/Previous buttons client onlick event

How can I add client (javascript) onclick event to Next/Previous links in DataPager?
You Can add a new button in data pager and worked on it's click event.
<asp:ListView runat="server" ID="ListView1"
DataSourceID="SqlDataSource1">
<LayoutTemplate>
<table runat="server" id=" table1">
<tr runat="server" id="itemPlaceholder">
</tr>
</table>
<!-- This is the pager. Define all necessary markup here. -->
<asp:DataPager runat="server" ID="DataPager" PageSize="5">
<Fields>
<asp:TemplatePagerField>
<PagerTemplate>
<asp:Button ID="btn_Submit" runat="server" Text="Button" onclientclick="eventHandler(this)" />
</PagerTemplate>
</asp:TemplatePagerField>
</Fields>
</asp:DataPager>
</LayoutTemplate>
</asp:ListView>
The answer above (by Sheery) works great for custom pager elements. However, when using the stock Numeric or Next/Previous pager styles of the ListView or DataGrid, you don't have near as much control. By using client-side jQuery/javascript selectors, you can unobtrusively attach client-side handlers to the pager elements. For this example, I'm tracking if any form field value has changed and if so, then prior to allowing the pager to execute it's default behavior of posting back to the server, we're confirming with the user that they have unsaved changes.
$(function () {
var _formChanged = false;
// grabs all pager links in last row of table named dgQuestions
// and attachs a click eventhandler via jQuery library
$("#dgQuestions tr:last a").click(function(e) {
if (!_formChanged)
return true;
var ok = confirm('You have UNSAVED changes. Continue?');
if (ok) {
return true;
}
else {
//Prevent the submit event and remain on the screen
e.preventDefault();
return false;
}
});
// delegates change event handling to the form to indicate if ANY
// form field value changed for testing prior to paging
$("#form1").change(function(e) {
_formChanged = true;
});
});
});
OR
Can also utilize the beforeunload event of the window to catch ANY navigate-away action to test for unsaved changes as well. This code excludes the actual click of the 'save' button.
$(window).on('beforeunload', function (e) {
if (e.originalEvent.explicitOriginalTarget.id != "btnSave") {
if (_formChanged)
return 'You have UNSAVED changes. Continue?';
}

asp.net postback prevented after clientside validation

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?');
}
}
}

Problem with textbox inside updatepanel - not causing OnTextChanged event

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>

Resources