Ajax UpdatePanel inside repeater is missing post back - c#

I can't do post back of the UpdatePanel inside the repeater.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Repeater ID="Posts" runat="server" OnItemCreated="Posts_OnItemCreated">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:Label ID="lblComentarios" runat="server" Text='<%# Eval("LabelComentarios") %>'></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click"/>
</Triggers>
</asp:UpdatePanel>
<asp:TextBox ID="txtComentario" runat="server" CssClass='<%# Eval("PostId") %>'></asp:TextBox>
<asp:Button ID="Button1" ClientIDMode="Static" runat="server" OnCommand="btnComentar_OnCommand" CommandName='<%# Eval("PostId") %>' class='<%# Eval("PostId") %>' />
</ItemTemplate>
</asp:Repeater>
Code for repeater OnItemCreated():
protected void Posts_OnItemCreated(object sender, RepeaterItemEventArgs e)
{
var control = e.Item.FindControl("Button1");
ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(control);
}
Then in my codebehind OnCommand ..
protected void btnComentar_OnCommand(object sender, CommandEventArgs e)
{
MyCode();
foreach (RepeaterItem item in Posts.Items)
{
var panel = (UpdatePanel)item.FindControl("UpdatePanel1");
panel.Update();
}
}
everything is doing what it should except panel.update().

I have done below code and its updating test values to label
ASPX:
<%# Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Repeater ID="Posts" runat="server" OnItemCreated="Posts_OnItemCreated">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblComentarios" runat="server" Text='<%# Eval("LabelComentarios") %>'></asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("LabelComentarios") %>'></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:TextBox ID="txtComentario" runat="server" CssClass='<%# Eval("PostId") %>'></asp:TextBox>
<asp:Button ID="Button1" ClientIDMode="Static" runat="server" OnCommand="btnComentar_OnCommand" CommandName='<%# Eval("PostId") %>' class='<%# Eval("PostId") %>' />
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
Code Behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.Add("LabelComentarios");
dt.Columns.Add("PostId");
dt.Rows.Add("esresrer");
dt.Rows.Add("esresrer");
dt.Rows.Add("esresrer");
Posts.DataSource = dt;
Posts.DataBind();
}
}
protected void Posts_OnItemCreated(object sender, RepeaterItemEventArgs e)
{
var control = e.Item.FindControl("Button1");
ScriptManager.GetCurrent(Page).RegisterAsyncPostBackControl(control);
}
protected void btnComentar_OnCommand(object sender, CommandEventArgs e)
{
//MyCode();
foreach (RepeaterItem item in Posts.Items)
{
var lbl = (Label)item.FindControl("Label1");
lbl.Text = "testest";
var panel = (UpdatePanel)item.FindControl("UpdatePanel1");
panel.Update();
}
}
}
}
Also check if !IsPostback proper or not

Related

ASP.NET FileUpload with precondtions (empty after PostBack)

I want to create a C# WebForm with a ASP.NET FileUpload Control and some Textboxes and a submit button. Idea: user selects a file, enters some data, on submit the form checks the data and if valid, it saves the file on the server otherwise an error message is displayed. There are so many posts about UpdatePanel Triggers etc. but not a working solution.
Here my code behind:
protected void Page_Load(object sender, EventArgs e) {
// for FileUpload-Control outside UpdatePanel
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void Button1_Click(object sender, EventArgs e) {
bool valid = true;
string errorMessage = DateTime.Now.ToLongTimeString() + ": ";
if (this.TextBox1.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox1<br/>";
}
if (this.TextBox2.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox2<br/>";
}
if (this.TextBox3.Text.Equals("")) {
valid = false;
errorMessage += "Missing Textbox3<br/>";
}
if (!this.FileUpload3.HasFile) {
// is alway false!
errorMessage += "Missing FileUpload3<br/>";
}
if (valid) {
// never fires, because .HasFile is always false
this.Label1.Text = "valid!";
// do upload stuff
this.FileUpload3.SaveAs("foobar");
} else {
this.Label1.Text = errorMessage;
}
}
And here is my sample ASPX:
<form id="Upload" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="FileUpload3" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Does anyone see, why my FileUpload is always empty, although it's outside the UpdatePanel and I do have the required line in the Page_Load() event? If, could you adjust the code?
Thank you
SiS
<form id="Upload" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:FileUpload ID="FileUpload3" runat="server" />
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>

Need to clear values of textboxes placed in update panel after button click

I have few textboxes in an update panel. On button click the values of textboxes is inserted into the database. I want the values to get cleared once the data has been inserted into the database.
PS: I tried to clear the values using a function after calling it once the data has been inserted. It doesn't work.
ASP
<%# Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="CalenderTest.aspx.cs" Inherits="DynamicCalender.CalenderTest" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 363px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1"runat="server"></asp:ToolkitScriptManager>
<div>
<div>
<asp:Label ID="lbl_year" runat="server" Text="Year"></asp:Label>
<asp:DropDownList ID="ddl_year" runat="server"></asp:DropDownList>
<asp:Label ID="lbl_train" runat="server" Text="Training"></asp:Label>
<asp:DropDownList ID="dd1_training" runat="server"></asp:DropDownList>
<asp:Button ID="btnsave" runat="server" Text="Create Batches" OnClick="btnsave_Click"/>
<br />
<br />
<asp:UpdatePanel ID="pnl1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="ss" runat="server" Text="session"></asp:Label>
<asp:Label runat="server" Text="Venue"></asp:Label>
<asp:TextBox ID="venue" runat="server" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="Time"></asp:Label>
<asp:DropDownList ID="ddltime" runat="server" ></asp:DropDownList>
<asp:Label ID="Label2" runat="server" Text="Faculty"></asp:Label>
<asp:TextBox ID="faculty" runat="server" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label3" runat="server" Text="Module Details"></asp:Label>
<asp:TextBox TextMode="MultiLine" id="module_det" runat="server" CausesValidation="false"></asp:TextBox>
<asp:Button id="Button1" runat="server" Text="Add" OnClick="Button1_Click" />
<asp:Button id="Button2" runat="server" Text="Next" OnClick="Button2_Click"/>
<asp:TextBox ID="caldt" runat="server" CausesValidation="false"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="caldt"></asp:CalendarExtender>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
<asp:HiddenField ID="hd01" runat="server" />
<asp:HiddenField ID="hd02" runat="server" />
</div>
</div>
C#
protected void Button1_Click(object sender, EventArgs e)
{
sess_datetime = caldt.Text + " " + ddltime.SelectedItem.Value.ToString();
str1 = "Insert into sessDetail (tid,bid,sid,dt,faculty,venue,status) values(#tid,#bid,#sid,#dt,#faculty,#venue,#status)";
cmd = new SqlCommand(str1, con);
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#tid", dd1_training.SelectedItem.Value);
cmd.Parameters.AddWithValue("#bid",Session["bid"]);
cmd.Parameters.AddWithValue("#sid",Session["sid"]);
cmd.Parameters.AddWithValue("#dt", sess_datetime);
cmd.Parameters.AddWithValue("#faculty", faculty.Text);
cmd.Parameters.AddWithValue("#venue", venue.Text);
cmd.Parameters.AddWithValue("#status", "0");
cmd.ExecuteNonQuery();
con.Close();
clear();
}
protected void clear
{
try
{
foreach (var pnl in pnl1.Controls)
{
var tb = pnl as TextBox;
if (tb != null)
{
tb.Text = "";
}
}
ddltime.ClearSelection();
}
catch(Exception x)
{
Response.Write(x.Message);
}
}
Wrap the Controls inside the UpdatePanel with a PlaceHolder and use that for the foreach loop.
<asp:UpdatePanel ID="pnl1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
Code behind
foreach (var pnl in PlaceHolder1.Controls)
{
//clear controls
}

SelectedIndexChanged event of dropDownList not firing in Update Panel

SelectedIndexChanged event of dropDownList not firing in Update Panel and also set AutoPostBack="true".
Below is my Design Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddl_TypeofCampaign" runat="server" CssClass="form-control" AutoPostBack="true" OnSelectedIndexChanged="ddl_TypeofCampaign_SelectedIndexChanged" AppendDataBoundItems="true" ViewStateMode="Enabled" EnableViewState="true" >
<asp:ListItem Text="Select" Value="0"></asp:ListItem>
<asp:ListItem Text="Email" Value="Email"></asp:ListItem>
<asp:ListItem Text="SMS" Value="SMS"></asp:ListItem>
<asp:ListItem Text="Voice SMS" Value="Voice SMS"></asp:ListItem>
</asp:DropDownList>
<asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1"
DisplayAfter="1">
<ProgressTemplate>
<div id="IMGDIV" runat="server" align="center" style="visibility: visible; vertical-align: middle; position: absolute; background-color: #fafbf6"
valign="middle">
<asp:Image ID="Image001" runat="server" ImageUrl="~/assets/img/ajax-loader.gif" />
</div>
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
protected void ddl_TypeofCampaign_SelectedIndexChanged(object sender, EventArgs e)
{
Thread.Sleep(2000);
FillTemplates();
btn_Preview.Visible = false;
}
My page Load code.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
FillTypeofSourcing();
FillCampaignNames();
FillTemplates();
}
}
Fill Template method where I am getting templates name base on selection.
protected void FillTemplates()
{
if (ddl_TypeofCampaign.SelectedItem.ToString() != "Select")
{
bo.Para1 = ddl_TypeofCampaign.SelectedItem.ToString();
bo.Para2 = "Stage1";//StageValue in TemplateMasterInfo Table
DataTable dt = bl.Get_Templates(bo);
ddl_TypeofTemplateName.DataSource = dt;
ddl_TypeofTemplateName.DataTextField = "TemplateName";
ddl_TypeofTemplateName.DataValueField = "TemplateId";
ddl_TypeofTemplateName.Items.Clear();
ddl_TypeofTemplateName.Items.Add(new ListItem("Select", "0"));
ddl_TypeofTemplateName.DataBind();
}
else
{
ddl_TypeofTemplateName.Items.Clear();
ddl_TypeofTemplateName.Items.Add(new ListItem("Select", "0"));
ddl_TypeofTemplateName.DataBind();
}
}
In Page Tag I mention viewStateEncryptionMode="Never" and I am using Visual Studio 2013. Below is my Page Tag details.
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ViewCandidate.aspx.cs" Inherits="ViewCandidate" validateRequest="false" enableEventValidation="false" viewStateEncryptionMode="Never" %>
Try to add Trigger to your Update Panel like shown as below
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddl_TypeofCampaign"
EventName="SelectedIndexChanged" />
</Triggers>
UPDATE
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers> //this is missing in your code posted
<asp:AsyncPostBackTrigger ControlID="ddl_TypeofCampaign" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>mydropcode </ContentTemplate> </asp:UpdatePanel>

Items in Table are gone after a Postback

When ever i hide or show the Panel, the items i add (dynamically) to the Table are gone, and another thing is that when i try add new Row to the Table, it won't show it, it's overwriting the same Row, why ??.
Here's the CodeBehind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
DropDownList1.Items.Add(TextBox3.Text);
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Panel1.Visible == true)
Panel1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Panel1.Visible == false)
Panel1.Visible = true;
}
protected void Button4_Click(object sender, EventArgs e)
{
TableCell tdStudentName = new TableCell();
tdStudentName.Text = TextBox1.Text;
TableCell tdStudentCourse = new TableCell();
tdStudentCourse.Text = DropDownList1.SelectedValue;
TableCell tdStudentGrade = new TableCell();
tdStudentGrade.Text = TextBox2.Text;
TableRow tr = new TableRow();
tr.Cells.Add(tdStudentName);
tr.Cells.Add(tdStudentCourse);
tr.Cells.Add(tdStudentGrade);
Table1.Rows.Add(tr);
}
}
}
Here's the Html Source:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Student Name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Course:"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add Course" />
<br />
<asp:Label ID="Label3" runat="server" Text="Grade:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button4" runat="server" OnClick="Button4_Click" Text="Add" />
<br />
<br />
<asp:Panel ID="Panel1" runat="server" GroupingText="Course Settings" Visible="False">
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Add" />
<asp:Button ID="Button3" runat="server" OnClick="Button3_Click" Text="Close" />
</asp:Panel>
<br />
<br />
<asp:Table ID="Table1" runat="server" BorderStyle="Solid">
<asp:TableRow runat="server">
<asp:TableCell runat="server">Name</asp:TableCell>
<asp:TableCell runat="server">Course</asp:TableCell>
<asp:TableCell runat="server">Grade</asp:TableCell>
</asp:TableRow>
</asp:Table>
</div>
</form>
</body>
</html>
Here's a preview of how it looks like:
If you add anything dynamically, then you must re-add it on any subsequent post-back. They will not automatically just "be there" on the next post-back.
This requires you to store the fact that the dynamic controls have been created and added, and therefore allows you to detect that on the post-back and add the controls back in again.
It is better (if possible) to add dynamic controls as part of the init stage of the life cycle, as this will mean they will pick up view state information before the load stage.
Edit
In response to the comment by the OP...
Where do i store these controls ? and where do i add them back ? inside Page_Load ?
You don't store the controls... you store the fact that the controls have been added.
The "easiest" way would be to use the ViewState, but that puts you in a catch-22 situation... because the ViewState is not available at the init stage of the life cycle, which is the preferred place to re-add those controls.
Another option would be to "store the fact" within an <asp:HiddenField> which you can check for within the init stage. However you would have to get the value directly from the Request object, as the field would not have the correct .Value at the init stage. You'd do that like...
if (!Page.IsPostBack)
{
string hdnValue = Request[hdnFieldCtrl.UniqueId];
// Recreate controls based on the details you need
}

ASP UpdatePanel doesn't work when used in ContentPage

My code works fine when used in a normal webform. but when I use it in a webform using masterpages, It doesn't work.
page header : ~/Manager/BaseManager.master
and some nested master pages : Base.master > Pages.master > BaseManager.master
ASP
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger EventName="Click"
ControlID="btnUpdateEditPage" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnUpdateEditPage" CssClass="btnUpdateEditPage" runat="server"
Text="Button" OnClick="btnUpdateEditPage_Click" />
C#
protected void btnUpdateEditPage_Click(object sender, EventArgs e)
{
lblTest.Text += "**";
}
Do the following please:
1- Add UpdatePanel1.Update(); like the following:
protected void btnUpdateEditPage_Click(object sender, EventArgs e)
{
lblTest.Text += "**";
UpdatePanel1.Update();
//Your UpdatePanel should be UpdateMode="Conditional" as what you have now..
}
2- Put the button inside the update Panel
3- Remove the Trigger to not fire a post back, so your code has to be like:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
<asp:Button ID="btnUpdateEditPage" CssClass="btnUpdateEditPage" runat="server"
Text="Button" OnClick="btnUpdateEditPage_Click" />
</ContentTemplate>
</asp:UpdatePanel>
Place the button inside UpdatePanel.
SOLVED.
I change
<form id="form1" runat="server" action="post">
to
<form id="form1" runat="server">
and my problem solved.
But why?!

Categories