UpdatePanel, Repeater, DataBinding Problem - asp.net

In a user control, I've got a Repeater inside of an UpdatePanel (which id displayed inside of a ModalPopupExtender. The Repeater is databound using an array list of MyDTO objects. There are two buttons for each Item in the list. Upon binding the ImageURL and CommandArgument are set.
This code works fine the first time around but the CommandArgument is wrong thereafter. It seems like the display is updated correctly but the DTO isn't and the CommandArgument sent is the one that has just been removed.
Can anybody spot any problems with the code?
Edit : I've just added a CollapsiblePanelExtender to the code. When I now delete an item and expand the panel, the item that was previously deleted (and gone from the display) has come back. It seems that the Repeater hasn't been rebuilt correctly under the bonnet.
ASCX
<asp:UpdatePanel ID="ViewDataDetail" runat="server" ChildrenAsTriggers="true">
<Triggers>
<asp:PostBackTrigger ControlID="ViewDataCloseButton" />
<asp:AsyncPostBackTrigger ControlID="DataRepeater" />
</Triggers>
<ContentTemplate>
<table width="100%" id="DataResults">
<asp:Repeater ID="DataRepeater" runat="server" OnItemCommand="DataRepeater_ItemCommand" OnItemDataBound="DataRepeater_ItemDataBound">
<HeaderTemplate>
<tr>
<th><b>Name</b></th>
<th><b> </b></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<b><%#((MyDTO)Container.DataItem).Name%></b>
</td>
<td>
<asp:ImageButton CausesValidation="false" ID="DeleteData" CommandName="Delete" runat="server" />
<asp:ImageButton CausesValidation="false" ID="RunData" CommandName="Run" runat="server" />
</td>
</tr>
<tr>
<td colspan="2">
<table>
<tr>
<td>Description : </td>
<td><%#((MyDTO)Container.DataItem).Description%></td>
</tr>
<tr>
<td>Search Text : </td>
<td><%#((MyDTO)Container.DataItem).Text%></td>
</tr>
</table>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind
public DeleteData DeleteDataDelegate;
public RetrieveData PopulateDataDelegate;
public delegate ArrayList RetrieveData();
public delegate void DeleteData(String sData);
protected void Page_Load(object sender, EventArgs e)
{
//load the initial data..
if (!Page.IsPostBack)
{
if (PopulateDataDelegate != null)
{
this.DataRepeater.DataSource = this.PopulateDataDelegate();
this.DataRepeater.DataBind();
}
}
}
protected void DataRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
if (DeleteDataDelegate != null)
{
DeleteDataDelegate((String)e.CommandArgument);
BindDataToRepeater();
}
}
else if (e.CommandName == "Run")
{
String sRunning = (String)e.CommandArgument;
this.ViewDataModalPopupExtender.Hide();
}
}
protected void DataRepeater_ItemDataBound(object source, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item != null && item.DataItem != null)
{
MyDTO oQuery = (MyDTO)item.DataItem;
ImageButton oDeleteControl = (ImageButton) item.FindControl("DeleteData");
ImageButton oRunControl = (ImageButton)item.FindControl("RunData");
if (oDeleteControl != null && oRunControl !=null)
{
oRunControl.ImageUrl = "button_expand.gif";
oRunControl.CommandArgument = "MyID";
if (oQuery !=null)
{
//do something
}
oDeleteControl.ImageUrl = "btn_remove.gif";
oDeleteControl.CommandArgument = "MyID";
}
}
}
public void BindDataToRepeater()
{
this.DataRepeater.DataSource = this.PopulateDataDelegate();
this.DataRepeater.DataBind();
}
public void ShowModal(object sender, EventArgs e)
{
BindDataToRepeater();
this.ViewDataModalPopupExtender.Show();
}

Thanks for reminding me why I stopped using ASP.NET controls. This is the exact type of nightmare that has made too many projects go way over budget and schedule.
My advise to you is to think of the simplest way to implement this. You can try to bend over backwards in order to get this to work the ASP.NET way or take the shortest route.
All you're doing is generating HTML, it should never be that difficult.
The most likely cause of your problem is that the ViewState is stored in the page which doesn't get updated on a partial postback. So with every change in the update panel you'll postback the initial viewstate of the page.
Try replacing the repeater with a simple for-loop (and ignore the people who start complaining you shouldn't mix markup and code). Replace your databinding statements with <%= %>.
That eliminates the view state all together and should remove any removed row from re-appearing.

After many days of messing around with this I've not found a proper fix for the problem but do have a workable work-around.
The CollapsiblePanelExtender is set to NOT postback automatically which fixes the issue of the deleted data re-appearing when the extender is opened. The other issue, I believe, is related.
It seems that the ViewState for the Repeater is out of sync with the data. e.CommandArgument is not always correct and seems to reference the previous data. I made an attempt to fix it by storing the ArrayList of MyDTO objects in the ViewState when opening the Modal dialog and using the ID retrieved from e.Item.ItemIndex to find the correct element to delete. This didn't work correctly, the ArrayList pulled out of the ViewState was out of sync.
Storing the ArrayList in the session makes it all work which leads me to believe that I'm doing something fundamentally wrong or there is a subtle bug in the version of the toolkit that i'm using (we're still on VS2005 so are stuck with an older version of the toolkit)
Apologies if this makes no sense, contact me if you want clarification on anything.

try using
((IDataItemContainer)Container).DataItem
instead of "Container.DataItem"
It worked for me.

Related

Repeater ItemCommand does not work on large data

I have a webform that shows a list of items using a repeater and there is a Edit button associated with each item.
By clicking the Edit button, the page is redirected to the Edit page
Html
<asp:Repeater ID="r epeaterRequest" runat="server">
<ItemTemplate>
<asp:LinkButton ID="btnEdit" CommandArgument='<%# Eval("ItemID") %>' CommandName="Edit" runat="server">Edit</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
Code Befind
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Page.IsPostBack == false)
{
List<MyItem> data = new repository().getData();
repeater.DataSource = data;
repeater.DataBind();
}
}
private void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int itemId;
if (int.TryParse(e.CommandArgument.ToString(), out itemId))
{
if (e.CommandName == "Edit")
{
Response.Redirect("~/Edit.aspx?id=" + itemId, false);
}
}
}
The problem is that when the number of list items gets larger like 2800 items in the List, it halts after clicking the Edit button. The ItemCommand does not get called or takes too long to get to the ItemCommand function.
(Loading and rendering the data is quick. It halts when the Edit button is clicked.
Everything is okay when there are less items like 1000.
I've tried adding this <httpRuntime maxRequestLength="102400" executionTimeout="300" /> to Web.Config but did not work.
Have you tried to add some simple paging to your repeater. That is a lot of data to load into the DOM at once. See this for an idea.
Why don't you change your LinkButton to simple hyperlink?
<asp:Repeater ID="r epeaterRequest" runat="server">
<ItemTemplate>
<a href='<%# Eval("href") %>'>Edit</a>
</ItemTemplate>
</asp:Repeater>
I think it is better solution in your case. Caz' you are doing the same, but using another way.

ListView + ObjectDataSource SelectMethod called twice when EnableViewState="false"

Note: This question has been completely modified now that I have a simpler example.
I have set up a sample page which only has a ListView and ObjectDataSource. The first time the page comes up (!IsPostBack), my GetList method is called once. After paging (IsPostBack), the GetList method is called twice--the first time with the old paging values and the second time with the new values.
If I set EnableViewState="true" on the ListView, then the GetList method is only called once. It seems to me that the ListView wants an "initial state", which it either gets from ViewState or by re-running the method.
Is there any way to disable ViewState on the ListView and also prevent SelectMethod from being called twice?
ASPX page:
<asp:ListView ID="TestListView" runat="server" DataSourceID="ODS" EnableViewState="false">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
<asp:DataPager ID="TestPager" runat="server" PageSize="10">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<div><%# Eval("Title") %></div>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ODS" runat="server" SelectMethod="GetList" SelectCountMethod="GetListCount"
TypeName="Website.Test" EnablePaging="true" />
ASPX code-behind:
namespace Website
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public IList<DataItem> GetList(int maximumRows, int startRowIndex)
{
return GetListEnumerable().Skip(startRowIndex).Take(maximumRows).ToList();
}
public IEnumerable<DataItem> GetListEnumerable()
{
for (int i = 0; i < 100; i++)
{
yield return new DataItem { Title = i.ToString() };
}
}
public int GetListCount()
{
return 100;
}
}
public class DataItem
{
public string Title { get; set; }
}
}
Either turn ODS caching on.
<asp:ObjectDataSource ID="ODS" ... EnableCaching="true" />
This way the GetList will be called only when new data is needed. Post backs to pages that already had data retrieved will use the cached version and not call the GetList.
Or move your DataPager out of the ListView and set the PagedControlID property.
Actually you should be using the OnSelecting event.
What happens is that ObjectDataSource calls the method SelectMethod twice
First time it gets the data.
Next time it gets the count.
So I think you have to implement the OnSelecting event
<asp:ObjectDataSource ID="ODS" runat="server" SelectMethod="GetList" SelectCountMethod="GetListCount"
OnSelecting="ods_Selecting">
TypeName="Website.Test" EnablePaging="true" />
and then cancel the event when the ObjectDataSource tries to call the count method.
protected void ods_Selecting(object sender,
ObjectDataSourceSelectingEventArgs e)
{
if (e.ExecutingSelectCount)
{
//Cancel the event
return;
}
}
You can look for full implementation as mentioned in the link below
http://www.unboxedsolutions.com/sean/archive/2005/12/28/818.aspx
Hope this helps.
I had a similar problem where it worked different depending on browser. IE one way and all other browsers one way.. Might not be the same issue as you have.
I solved it this way:
protected void DropDownDataBound(object sender, EventArgs e)
{
// Issue with IE - Disable ViewState for IE browsers otherwhise the dropdown will render empty.
DropDownList DDL = (DropDownList)sender;
if (Request.Browser.Browser.Equals("IE", StringComparison.CurrentCultureIgnoreCase))
DDL.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
else
DDL.ViewStateMode = System.Web.UI.ViewStateMode.Inherit;
}

ASP.NET - Control Events Not Firing Inside Repeater

This is a absurdly common issue and having exhausted all of the obvious solutions, I'm hoping SO can offer me some input... I have a UserControl inside a page which contains a repeater housing several controls that cause postback. Trouble is, all of the controls inside of the repeater never hit their event handlers when they postback, but controls outside of the repeater (still in the UC) are correctly handled. I already made sure my controls weren't being regenerated due to a missing if(!IsPostBack) and I verified that Request.Form["__EVENTTARGET"] contained the correct control ID in the Page_Load event. I attempted to reproduce the symptoms in a separate project and it worked as it should.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="NoteListControl.ascx.cs"
Inherits="SantekGBS.Web.UserControls.NoteListControl" %>
<asp:UpdatePanel ID="upNotes" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="NoteList" id="divNoteList" runat="server">
<asp:Repeater ID="repNotes" runat="server">
<HeaderTemplate>
<table width="98%" cellpadding="3" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr class="repeaterItemRow">
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Content/images/DeleteIcon.gif"
OnClick="ibRemove_Click" CommandArgument='<%# Container.ItemIndex %>' CommandName='<%# Eval("ID") %>'
CausesValidation="false" AlternateText="Delete" />
<%# Eval("Text") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:PlaceHolder ID="phNoNotes" runat="server" Visible="false">
<div class="statusMesssage">
No notes to display.
</div>
</asp:PlaceHolder>
</div>
</ContentTemplate>
</asp:UpdatePanel>
public partial class NoteListControl : UserControl
{
[Ninject.Inject]
public IUserManager UserManager { get; set; }
protected List<Note> Notes
{
get
{
if (ViewState["NoteList"] != null)
return (List<Note>)ViewState["NoteList"];
return null;
}
set { ViewState["NoteList"] = value; }
}
public event EventHandler<NoteEventArgs> NoteAdded;
public event EventHandler<NoteEventArgs> NoteDeleted;
public event EventHandler<NoteEventArgs> NoteChanged;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
UtilityManager.FillPriorityListControl(ddlPriority, false);
}
}
protected void ibRemove_Click(object sender, ImageClickEventArgs e)
{
System.Diagnostics.Debug.WriteLine("ibRemove POSTBACK"); // This is NEVER hit
}
public void Fill(List<Note> notes)
{
Notes = notes;
RefreshRepeater();
}
private void RefreshRepeater()
{
if (Notes != null && Notes.Any())
{
var sorted = Notes.OrderByDescending(n => n.Timestamp);
Notes = new List<Note>();
Notes.AddRange(sorted);
repNotes.Visible = true;
phNoNotes.Visible = false;
repNotes.DataSource = Notes;
repNotes.DataBind();
}
else
{
repNotes.Visible = false;
phNoNotes.Visible = true;
}
}
}
public class NoteEventArgs : EventArgs
{
public Note Note { get; set; }
public NoteEventArgs()
{ }
public NoteEventArgs(Note note)
{
this.Note = note;
}
}
The code is intentionally missing functionality so just disregard that fact.
Your edited code has residual CommandArgument and CommandName properties; are you actually handling the Repeater.ItemCommand event?
If so, and if your page calls the control's Fill method on postbacks, that would explain it.
This classic ASP.NET hair-tearing problem is explained in these posts: A Stumper of an ASP.NET Question and A Stumper of an ASP.NET Question: SOLVED!
The explanation is a little mind-bending, but the crux of it is that Repeater.DataBind interferes with ASP.NET's ability to determine which repeater button caused a postback.
I found a missing td-tag in the Itemtemplate, sometimes when DOM is incorrect, the updatapanel do strange things.
Just about EVERY time I run into this problem it's because DataBind() is being called when it shouldn't be. This will kill most events from controls inside a repeater. I see you have an !IsPostBack check in your Page_Load... so that's a start. But try putting a breakpoint on repNotes.DataBind() and see if it's getting called when you don't expect it.
Does it work OK outside of an UpdatePanel?
I ran into the same problem. It happened with me if I've ran the DataBind twice. In other words when I populate the repeater control twice (for any reason) the events wont fire.
I hope that helps.

ASP.Net and two-way data binding

I've created a class library which exposes my back-end object model. I don't wish to databind straight to SQL or XML, as a surprising number of tutorials/demos out there seem to assume.
In my Page_Load(), within the if (!IsPostbak), I currently set all the values of my controls from the object model, and call Databind() on each control.
I have a button event handler which deletes an item from the object model (it's a List in this case) and rebinds it to the Repeater. First of all, this is messy - rebinding each time - but more importantly, no values are displayed when the page reloads. Should I put the databinding code outside the if statement in Page_Load()?
The second part of the question is regarding going back to basics - what's the best way to databind in Asp.net? I'm mainly interested in binding against lists and arrays. I would have imagined there being a way to tell a control (e.g. TextBox) to databind to a string variable, and for the string to always reflect the contents of the text box, and the text box to always reflect the contents of the string. I tried the <%#...%> syntax but got no further than using the code-behind as described above.
I've read several overviews of databinding, but nothing out there seems to do what I want - they all talk about linking DataSets to a SQL database!
Turning to the knowledge of StackOverflow.
You'll need to databind on every page load so you need to remove the code from within your !IsPostBack block.
When using a list or array handle the databinding event on the control. For a repeater you'll need to handle the ItemDataBound event.
This example has been modified from http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound.aspx:
<%# Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<title>OnItemDataBound Example</title>
<script language="C#" runat="server">
void Page_Load(Object Sender, EventArgs e) {
ArrayList values = new ArrayList();
values.Add(new Evaluation("Razor Wiper Blades", "Good"));
values.Add(new Evaluation("Shoe-So-Soft Softening Polish", "Poor"));
values.Add(new Evaluation("DynaSmile Dental Fixative", "Fair"));
Repeater1.DataSource = values;
Repeater1.DataBind();
}
void R1_ItemDataBound(Object Sender, RepeaterItemEventArgs e) {
// This event is raised for the header, the footer, separators, and items.
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
if (((Evaluation)e.Item.DataItem).Rating == "Good") {
((Label)e.Item.FindControl("RatingLabel")).Text= "<b>***Good***</b>";
}
}
}
public class Evaluation {
private string productid;
private string rating;
public Evaluation(string productid, string rating) {
this.productid = productid;
this.rating = rating;
}
public string ProductID {
get {
return productid;
}
}
public string Rating {
get {
return rating;
}
}
}
</script>
</head>
<body>
<h3>OnItemDataBound Example</h3>
<form id="form1" runat="server">
<br />
<asp:Repeater id="Repeater1" OnItemDataBound="R1_ItemDataBound" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<td><b>Product</b></td>
<td><b>Consumer Rating</b></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td> <asp:Label Text='<%# DataBinder.Eval(Container.DataItem, "ProductID") %>' Runat="server"/> </td>
<td> <asp:Label id="RatingLabel" Text='<%# DataBinder.Eval(Container.DataItem, "Rating") %>' Runat="server"/> </td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
</form>
</body>
</html>
EDIT:
In addition, (and you may already be aware of this) you'll need to persist your list/array somehow. You can go all the way back to the database and reconstitute the list there or you can store it in memory with cache, viewstate, or session as viable options depending on your needs.
Spring.NET Web will provide you with two-way databinding with nice, easy to maintain code. Give it a try!

ASP.NET AJAX Toolkit - CalendarExtender is reset on Postback

I have an ASP.NET page that has two input elements:
A TextBox that is ReadOnly. This TextBox is the TargetControl of a CalendarExtender
A DropDownList with AutoPostBack=true
Here is the code:
<table border="0" cellpadding="0" cellspacing="0">
<tr><td colspan="2">Date:</td></tr>
<tr><td colspan="2">
<asp:TextBox ID="dateTextBox" runat="server" ReadOnly="true" />
<ajax:CalendarExtender ID="datePicker" runat="server" Format="MM/dd/yyyy" OnLoad="datePicker_Load" TargetControlID="dateTextBox" />
</td></tr>
<tr><td colspan="2">Select an Option:</td></tr>
<tr>
<td>Name: </td>
<td><asp:DropDownList ID="optionsDropDownList" runat="server" AutoPostBack="true"
OnLoad="optionsDropDownList_Load"
OnSelectedIndexChanged="optionsDropDownList_SelectedIndexChanged"
DataTextField="Name" DataValueField="ID" />
</td></tr>
<tr><td><asp:Button ID="saveButton" runat="server" Text="Save" OnClick="saveButton_Click" /></td></tr>
</table>
When the DropDownList posts back, the date selected by the user with the datePicker is reset to the current date. In addition, if I look at the Text property of dateTextBox, it is equal to string.Empty.
How do I preserve the date that the user selected on a PostBack?
Certainly you must do as others have already suggested: set readonly field dynamically rather than in markup, and make sure you are not accidentally resetting the value in Page_Load() during postbacks...
...but you must also do the following inside Page_Load(), because the CalendarExtender object has an internal copy of the date that must be forcibly changed:
if (IsPostBack) // do this ONLY during postbacks
{
if (Request[txtDate.UniqueID] != null)
{
if (Request[txtDate.UniqueID].Length > 0)
{
txtDate.Text = Request[txtDate.UniqueID];
txtDateExtender.SelectedDate = DateTime.Parse(Request[txtDate.UniqueID]);
}
}
}
The fact that the text box is read only appears to be causing this problem. I duplicated your problem using no code in any of the bound events, and the date still disappeared. However, when I changed the text box to ReadOnly=False, it worked fine. Do you need to have the textbox be read only, or can you disable it or validate the date being entered?
EDIT: OK, I have an answer for you. According to this forum question, read only controls are not posted back to the server. So, when you do a postback you will lose the value in a read only control. You will need to not make the control read only.
protected void Page_Load(object sender, EventArgs e)
{
txt_sdate.Text = Request[txt_sdate.UniqueID];
}
If you want the textbox contents remembered after the postback and still keep it as readonly control, then you have to remove the readonly attribute from the markup, and add this in the codebehind pageload:
protected void Page_Load(object sender, EventArgs e){
TextBox1.Attributes.Add("readonly", "readonly");
// ...
}
The solution to the issue is making use of Request.Form collections. As this collection has values of all fields that are posted back to the server and also it has the values that are set using client side scripts like JavaScript.
Thus we need to do a small change in the way we are fetching the value server side.
C#
protected void Submit(object sender, EventArgs e)
{
string date = Request.Form[txtDate.UniqueID];
}
I suspect your datePicker_Load is setting something and not checking if it's in a postback. That would make it happen every time and look like it was 'resetting'.
In stead of setting ReadOnly="False", set Enabled="False". This should fix your issue.
#taeda's answer worked for me. FYI, if someone uses enabled = "false" instead of readonly = "true" wont be able to use that answer, because Request[TxtDate.UniqueId] will throw a null exception.
It is not a problem of Preserving,after setting readonly = true the value of the particular textbox doesn't be returned back to server
so
Use contentEditable="false" and made readonly = false
that would prevent value is being entered other than Calendar Extender selection also returns the value of the Text box back to the server

Resources