ASP.NET AJAX Doesnt Work - asp.net

I have a very simple AJAX example that doesn't work.
It is from the Microsoft tutorials on AJAX.
When I click on button "Button1" AJAX should execute but the whole page submits.
Here is the code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="1111.aspx.cs" Inherits="_1111" %>
<%# Register Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<p>
DropDownList AutoPostBack SelectedIndexChanged EventArgs Sort ... Since you will
be using AJAX to process your SelectedIndexChanged event, set the AutoPostBack property
of the DropDownList to false. ...</p>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
</asp:ScriptManager>
<asp:Label ID="label2" runat="server"></asp:Label><br />
<asp:Label ID="label3" runat="server"></asp:Label><br />
<center>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="label1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button 1" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</center>
</div>
</form>
</body>
</html>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _1111 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
label1.Text = System.DateTime.Now.ToString();
label2.Text = System.DateTime.Now.ToString();
label3.Text = System.DateTime.Now.ToString();
}
protected void Button1_Click(object sender, EventArgs e)
{
label1.Text = System.DateTime.Now.ToString();
}
}

The code works for me.
The reason is possibly you are not configuring your web.config file properly. See what is inside your file.
It needs some components to support MS AJAX Extensions.
Go to
http://www.asp.net/ajax/videos/how-do-i-add-aspnet-ajax-features-to-an-existing-web-application.
Have a look at the tutorial to see if that helps.

I think your misunderstanding is in the Page_Load event, which will always fire, even for partial post-backs. You can handle that by making any initialization code conditional, as in:
if (!IsPostBack) {
label1.Text = System.DateTime.Now.ToString();
label2.Text = System.DateTime.Now.ToString();
label3.Text = System.DateTime.Now.ToString();
}

Related

Asp Timer with AsyncPostBackTrigger on child ascx page causes Default.aspx to reload

What i'm trying to accomplish is a partial page reload on just an child ascx control. However, if I put a break on default.aspx on Page Load the break will hit on the timer tick. My ideal scenario would be the default.aspx never reloads.
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.Core.js" />
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQuery.js" />
<asp:ScriptReference Assembly="Telerik.Web.UI" Name="Telerik.Web.UI.Common.jQueryInclude.js" />
</Scripts>
</telerik:RadScriptManager>
<script type="text/javascript">
//Put your JavaScript code here.
</script>
<div>
<asp:Label runat="server" ID="DynLabel"></asp:Label>
<asp:PlaceHolder ID="PlaceHolderDyn" runat="server"></asp:PlaceHolder>
</div>
</form>
Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Guid g;
g = Guid.NewGuid();
DynLabel.Text = g.ToString();
PlaceHolderDyn.Controls.Add(LoadControl("~/Docks/DynControl.ascx"));
}
}
DynControl.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="DynControl.ascx.cs" Inherits="Docks_DynControl" %>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="Timer1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadGrid1" LoadingPanelID="LoadingPanel1">
</telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
<telerik:AjaxSetting AjaxControlID="DropDownList1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="Panel1"></telerik:AjaxUpdatedControl>
<telerik:AjaxUpdatedControl ControlID="Panel2"></telerik:AjaxUpdatedControl>
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<telerik:RadAjaxLoadingPanel ID="LoadingPanel1" runat="server">
</telerik:RadAjaxLoadingPanel>
<asp:Timer ID="Timer1" runat="server" Interval="3000" OnTick="Timer1_Tick"></asp:Timer>
<asp:UpdatePanel ID="Panel1" runat="server" UpdateMode="Conditional" ViewStateMode="Enabled">
<ContentTemplate>
<asp:PlaceHolder ID="DynamicPlaceHolder" runat="server"></asp:PlaceHolder>
<asp:Labelrunat="server" ID="DynamiclabelAscx"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
DynControl.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.Web.UI;
public partial class Docks_DynControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Timer1_Tick(object sender, EventArgs e)
{
Guid g;
g = Guid.NewGuid();
DynamiclabelAscx.Text = g.ToString();
}
}
So basically the label on the Default.aspx will be static, only load once, and the timer will reload the label on the ascx and it will always change. That works, but how can i prevent the default.aspx from reloading on the timer?
Thanks!
After doing some research, here is the answer to your question:
An asynchronous postback behaves much like a synchronous postback. All
the server page life-cycle events occur, and view state and form data
are preserved. However, in the rendering phase, only the contents of
the UpdatePanel control are sent to the browser. The rest of the page
remains unchanged.
MSDN Source
So wrapping the Default.aspx Page_Load method in !IsPostBack seems to be the way to go:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Guid g;
g = Guid.NewGuid();
DynLabel.Text = g.ToString();
PlaceHolderDyn.Controls.Add(LoadControl("~/Docks/DynControl.ascx"));
}
}
Thanks to Scott for the extended conversation.
The best way I've figured out to prevent postback is to have everything contained in that additional control aspx/ascx in an IFrame that points to that aspx. This will cause only that page to render any postback.

how to change the inner html of a div

i have a div and an html editor and trying to:
add the div inner html to the
editor. (thats done)
then any changes done in the editor
is saved back in the div.
here is the backcode :
protected void Page_Load(object sender, EventArgs e)
{
Editor.Content = cvDiv.InnerHtml;
}
protected void preview(object sender, EventArgs e) //this is an onclick event
{
cvDiv.InnerHtml = Editor.Content;
}
and the code for the editor:
<asp:ScriptManager runat="server" />
<cc1:Editor ID="Editor" runat="server" OnContentChanged="preview" />
<asp:Button runat="server" ID="eButton" CssClass="eButton" Text="Edit" OnClick="Edit" />// this is the button that is supposed to save
but it doesnt work.
so what i am trying to do is save whatever changes made in the editor to the div
using asp.net 3.5, and the ajax toolkit editor.
thanks in advance.
This is an example i've made to show you a working code.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
<asp:TextBox id="editor" runat="server" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Save" runat="server" OnClick="SaveChange" Text="Save" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
<ContentTemplate>
<div id="preview" runat="server"></div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="editor" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
ASPX.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) editor.Text = preview.InnerHtml;
else preview.InnerHtml = editor.Text;
}
protected void SaveChange(object sender, EventArgs e)
{
string thingsToSave = preview.InnerHtml;
//Save to db/file/xml
}
}
Can you try using Literal control rather than a server side <div /> ?

Cant seem to hide TableRow on AJAX postback

I wolud like to hide/unhide a TableRow through ASP.NET AJAX when a checkbox is clicked.
I have this code for the checkbox:
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:CheckBox runat="server" ID="cbViewPages" Checked="true" OnCheckedChanged="OnViewPages" AutoPostBack="true"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbViewPages" EventName="CheckedChanged"/>
</Triggers>
</asp:UpdatePanel>
and this for the TableRow
<asp:TableRow runat="server" ID="PagesRow">
<asp:TableCell VerticalAlign="Middle">Test Row</asp:TableCell>
</asp:TableRow>
This method is called when the checkbox is clicked:
protected void OnViewPages(object sender, EventArgs e)
{
if(cbViewPages.Checked)
{
PagesRow.Visible = true;
}
else
{
PagesRow.Visible = false;
}
}
OnViewPages is definitely called, I can see that through the debugger.
And if I remove the AJAX code, OnViewPages is hidden/unhidden as required.
Why doesn't this hide/unhide functionality work with the AJAX code?
Doh!
I have a partial answer, the TableRow is not in the Update panel.
But you cant put an UpdatePanel around a TableRow.
So that's my new question, how do you put an UpdatePanel around a TableRow?
A couple of options. You could put the update panel around the entire table (this is what Petras is suggesting). You could also use JavaScript to do this. In the event that fires when your checkbox is checked/unchecked, just call
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "setRowVisibility", "setRowVisibility(" & IIf(cbViewPages.Checked, "true", "false") & ");", True)
This will call a JavaScript function you can define on your page like this:
function setRowVisiblity(visible) {
var row = document.getElementById('<%=PagesRow.ClientID %>');
if (visible) {
row.style.display = 'table-row';
} else {
row.style.display = 'none';
}
}
This is MUCH more efficient than using and Update Panel, but it's a little more work. I prefer efficiency, but that's just me. :)
Here's the solution:
ASPX page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptMgr" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:CheckBox runat="server" ID="cbViewPages" Checked="true" OnCheckedChanged="OnViewPages" AutoPostBack="true"/>
<asp:Table runat="server">
<asp:TableRow>
<asp:TableCell>123</asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server" ID="PagesRow">
<asp:TableCell>Row To Hide</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="cbViewPages" EventName="CheckedChanged"/>
</Triggers>
</asp:UpdatePanel>
</form>
</body>
</html>
Code behind page:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void OnViewPages(object sender, EventArgs e)
{
if(cbViewPages.Checked)
{
PagesRow.Visible = true;
}
else
{
PagesRow.Visible = false;
}
}
}

ModalPopupExtender and validation problems

The problem I am facing is that when there is validation on a page and I am trying to display a model pop-up, the pop-up is not getting displayed. And by using fire-bug I have noticed that an error is being thrown.
The button that is used to display the pop-up has cause validation set to false so I am stuck as to what is causing the error.
I have created a sample page to isolate the problem that I am having, any help would be greatly appreciated.
The Error
function () {Array.remove(Page_ValidationSummaries, document.getElementById("ValidationSummary1"));}(function () {var fn = function () {AjaxControlToolkit.ModalPopupBehavior.invokeViaServer("mpeSelectClient", true);Sys.Application.remove_load(fn);};Sys.Application.add_load(fn);}) is not a function
http://localhost:1131/WebForm1.aspx
Line 136
ASP
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="CLIck10.WebForm1" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:Button ID="btnPush" runat="server" Text="Push" CausesValidation="false" onclick="btnPush_Click" />
<asp:TextBox ID="txtVal" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtVal" ErrorMessage="RequiredFieldValidator" />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
<input id="popupDummy" runat="server" style="display:none" />
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</div>
</form>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CLIck10
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnOK_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
mpeSelectClient.Hide();
}
protected void btnPush_Click(object sender, EventArgs e)
{
mpeSelectClient.Show();
}
}
}
This is an issue with using both ValidationSummary and ModalPopup.
see here: http://ajaxcontroltoolkit.codeplex.com/WorkItem/View.aspx?WorkItemId=12835
The problem is that there is a missing ";" between the two injected scripts.
Their solution is to create/use a custom server control that inherits from ValidationSummary, that injects a ";" into the page startup script to fix the bug:
[ToolboxData("")]
public class AjaxValidationSummary : ValidationSummary
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), this.ClientID, ";", true);
}
}
Try setting your ValidationSummary "Enabled" property to false on this event : "btnPush_Click"
; and then setting it back to enabled = "true" on this events : "btnOK_Click" ,"btnCancel_Click".
I think this will work if you do not have the validation summary inside the Panel that you want to pop up.But it is not a solution if you need the validation summary inside the pop up panel,...witch is my case :(.
Best Regards.
I tried all the available answer online but didn't worked any. Then i tried to move my modal popup extender at very end of the HTML and it works fine for me. Me and my users are Happy :)
I am not using FROM tag I am using Content place holder just like below:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<table id="tblMessage" runat="server" width="100%" >
<tr align="center">
<td align="center">
main content and
<asp:Panel ID="pnlSelectClient" Style="display: none" CssClass="box" runat="server">
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
<asp:UpdatePanel ID="upnlSelectClient" runat="server">
<ContentTemplate>
<asp:Button ID="btnOK" runat="server" UseSubmitBehavior="true" Text="OK" CausesValidation="false" OnClick="btnOK_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="false" OnClick="btnCancel_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
If you notice i have validation summary inside the panel because i want error message inside the pop up(i have some additional control in pop up too). and
Some more HTML tag here as i have so many other things to do in one page. right before closing tag of TABLE
<ajaxToolkit:ModalPopupExtender ID="mpeSelectClient" runat="server"
TargetControlID="popupDummy"
PopupControlID="pnlSelectClient"
OkControlID="popupDummy"
BackgroundCssClass="modalBackground"
CancelControlID="btnCancel"
DropShadow="true" />
</table>
Done.it's working. Hope that works for other too.
Are you using validation groups anywhere on the page? I've had problems with control events not firing when they are not part of a validation group and other controls on the page are part of a validation group.
I'd try changing this:
<input id="popupDummy" runat="server" style="display:none" />
to something like this:
<asp:Button id="popupDummy" runat="server" CausesValidation="false" Visible="false" />
I bet the untyped input is requiring validation.
i had the same issue, adding ValidationGroup to the validation controls did the trick!
One other thing to try, if you don't need Client Script you can disable it in the markup. Doing that fixed our problem.
EnableClientScript="false"

Method calls with time interval (asp.net c#)

Hi I want to call a method based on one time span
here is my trail
protected void binddata(object sender, EventArgs e)
{
// my logic here
}
Now I want to call this method for every 5 mins
using c# and asp.net how can i achieve this?
thank you
you have a timer control in ASP.Net ajax controls.
http://msdn.microsoft.com/fr-fr/library/system.web.ui.timer.aspx
It provides a postbak
exemple from msdn:
<%# Page Language="C#" AutoEventWireup="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html >
<head runat="server">
<title>Timer Example Page</title>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
OriginalTime.Text = DateTime.Now.ToLongTimeString();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
StockPrice.Text = GetStockPrice();
TimeOfPrice.Text = DateTime.Now.ToLongTimeString();
}
private string GetStockPrice()
{
double randomStockPrice = 50 + new Random().NextDouble();
return randomStockPrice.ToString("C");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" OnTick="Timer1_Tick" runat="server" Interval="10000" />
<asp:UpdatePanel ID="StockPricePanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" />
</Triggers>
<ContentTemplate>
Stock price is <asp:Label id="StockPrice" runat="server"></asp:Label><BR />
as of <asp:Label id="TimeOfPrice" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<div>
Page originally created at <asp:Label ID="OriginalTime" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Hope this help.
Using System.Threading.Timer - http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx.
Timer myTimer = new Timer();
myTimer.Elapsed += new ElapsedEventHandler( binddata);
myTimer.Interval = 5*60*100;
myTimer.Start();

Resources