Alert not coming using timer in updatepanel - c#

I am using c# for programming!
Below is my aspx code where I am using timer control in UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline" UpdateMode="Always">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="20000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:HiddenField ID="hidCurrentDate" runat="server" />
<asp:HiddenField ID="hidTripIds" runat="server" />
<asp:HiddenField ID="hidTripDetails" runat="server" />
<asp:HiddenField ID="currPageNo" runat="server" Value="1" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
And below is the code of my aspx.cs for timer_tick event.
protected void Timer1_Tick(object sender, EventArgs e)
{
DataTable dtTrips = null;
WEX.Prototype.Data.TripDA tripDA = new WEX.Prototype.Data.TripDA();
TripSummaryBO tripSummaryBO = new TripSummaryBO();
string tID = hidTripIds.Value.TrimStart(',');
if (!string.IsNullOrEmpty(tID))
{
string[] tripIDs = tID.Split(',');
string status = string.Empty;
foreach (string tripID in tripIDs)
{
tripSummaryBO = tripDA.getTripSummary(Convert.ToInt32(tripID));
if (tripSummaryBO.tripLastEditedOnDate > Convert.ToDateTime(hidCurrentDate.Value))
{
if (string.IsNullOrEmpty(status))
{
status = tripSummaryBO.tripID.ToString();
}
else
{
status = status + "," + tripSummaryBO.tripID.ToString();
}
if (cnt == 0)
{
hidTripDetails.Value = ("Trip name-" + tripSummaryBO.tripName + " was modified by user " + tripSummaryBO.tripLastEditedBy);
}
else
{
hidTripDetails.Value = hidTripDetails.Value + "--" +("Trip name-" + tripSummaryBO.tripName + " was modified by user " + tripSummaryBO.tripLastEditedBy);
}
cnt = cnt + 1;
}
}
if (!string.IsNullOrEmpty(status))
{
string alertMessage = "alert('" + hidTripDetails.Value + "');";
Guid numb = Guid.NewGuid();
ScriptManager.RegisterClientScriptBlock(upTripsGrid, upTripsGrid.GetType(), numb.ToString(), alertMessage, true);
WEX.Prototype.Service.WSProxies WSProxies = new WEX.Prototype.Service.WSProxies();
dtTrips = WSProxies.Build();
Session["AllTrips"] = dtTrips;
dtTrips = (DataTable)Session["AllTrips"];
BuildGridViewControl(dtTrips);
}
hidCurrentDate.Value = DateTime.Now.ToString();
}
}
You can see that I am using below code for showing alert however its not coming up!
ScriptManager.RegisterClientScriptBlock(upTripsGrid, upTripsGrid.GetType(), numb.ToString(), alertMessage, true);
Please suggest!
Thanks.

What is "upTripsGrid" in you code?
If you're using this code, with the above aspx-code, try using "UpdatePanel1" instead of "upTripsGrid"?

Related

Dynamic TextBox TextChanged is not firing in UpdatePanel

My dynamic textboxes TextChanged event is working properly without using UpdatePanel, but when i use UpdatePanel it stops working. it works only when Button is clicked and when the LinkButton is clicked.
How can i set TextChanged event of dynamic textboxes as trigger for the UpdatePanel. I hope this is clear for you.
This is my aspx
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Name :"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Age :"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="Phones :"></asp:Label>
<br />
<asp:Panel ID="pnlTextBox" runat="server">
</asp:Panel>
<asp:LinkButton ID="btnAddTxt" runat="server" OnClick="btnAddTxt_Click">Add TextBox</asp:LinkButton>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="save" OnClick="Button1_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</form>
and this is code behind
protected void Page_PreInit(object sender, EventArgs e)
{
//Recreate Controls
RecreateControls("txtDynamic", "TextBox");
}
protected void btnAddTxt_Click(object sender, EventArgs e)
{
int cnt = FindOccurence("txtDynamic");
CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "TextBox")
{
CreateTextBox(ctrlID);
}
break;
}
}
}
}
}
private void CreateTextBox(string ID)
{
TextBox txt = new TextBox();
txt.ID = ID;
txt.AutoPostBack = true;
txt.TextChanged += new EventHandler(OnTextChanged);
pnlTextBox.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br /><br />";
pnlTextBox.Controls.Add(lt);
}
protected void OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
string ID = txt.ID;
//Place the functionality here
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + ID + " fired OnTextChanged event')", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtDynamic1 = (TextBox)this.form1.FindControl("txtDynamic-1");
TextBox txtDynamic2 = (TextBox)this.form1.FindControl("txtDynamic-2");
Response.Write(txtDynamic1.Text + " & " + txtDynamic2.Text);
}
You can refer to this URL and add the postback trigger from the code behind instead of the aspx. https://forums.asp.net/t/1124967.aspx?Adding+a+Trigger+to+an+UpdatePanel+in+code+behind

How to update an UpdatePanel with a trigger control from outside of it

I have the following button which is outside of the UpdatePanel that I would like use to update:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btnExport" ClientIDMode="Static" UseSubmitBehavior="false" OnClick="SubmitAdminMessage" />
<asp:UpdatePanel ID="upMessages" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
The code-behind:
protected void Page_Load(object sender, EventArgs e)
{
upMessages.Triggers.Add(new AsyncPostBackTrigger()
{
ControlID = btnSubmit.UniqueID,
});
PopulateMessageGV(); //this displays the message on refresh of the page
}
protected void SubmitAdminMessage(object sender, EventArgs e)
{
var hostWeb = Page.Request["SPHostUrl"];
using (var context = new ClientContext(hostWeb))
{
var hostSite = context.Web;
context.Load(hostSite, s => s.Title);
context.ExecuteQuery();
var allLists = hostSite.Lists;
var messageList = allLists.GetByTitle("AdminMessage");
var itemCreationInformation = new ListItemCreationInformation();
var newMessage = messageList.AddItem(itemCreationInformation);
newMessage["Message"] = tbMessage.Text;
newMessage["Active"] = cbIsActive.Checked.ToString();
newMessage.Update();
context.ExecuteQuery();
}
}
The following function updates the messages on page refresh:
protected void PopulateMessageGV()
{
Microsoft.SharePoint.Client.ListItemCollection filteredItems = null;
var hostWeb = Page.Request["SPHostUrl"];
using (var context = new ClientContext(hostWeb))
{
var hostSite = context.Web;
context.Load(hostSite, s => s.Title);
context.ExecuteQuery();
var allLists = hostSite.Lists;
var messageList = allLists.GetByTitle("AdminMessage");
context.Load(messageList);
context.ExecuteQuery();
MessageListCountLabel.Text = messageList.ItemCount.ToString();
ListUrlHyperLink.NavigateUrl = hostWeb + "/Lists/AdminMessage";
try
{
var query = CamlQuery.CreateAllItemsQuery();
var allItems = messageList.GetItems(query);
context.Load(allItems);
context.ExecuteQuery();
foreach (var item in allItems)
{
DataTable dt;
if (item["Active"].ToString() == "True")
{
msItem.Add(item["Created"].ToString() + " " + item["Message"].ToString());
}
}
msItem.ToArray();
foreach (var list in msItem)
{
lblMessage.Text += list + "<br />";
}
upMessages.Update();
}
catch (Exception ex)
{
string error = ex.Message;
}
try
{
var query = new CamlQuery();
var camlViewXml = string.Format(#"<View><Query><Where><Eq>
<FieldRef Name='Active'/><Value Type='Boolean'>
{0}</Value></Eq></Where>
</Query></View>", "False");
query.ViewXml = camlViewXml;
filteredItems = messageList.GetItems(query);
context.Load(filteredItems, items => items.Include(
item => item["ID"], item => item["Created"],
item => item["Message"]));
context.ExecuteQuery();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
}
How do I modify my code so that when the submit button is pressed the lblMessage is updated without having to refresh the page?
You can use external triggers like this
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btnExport" ClientIDMode="Static" UseSubmitBehavior="false" OnClick="SubmitAdminMessage" />
<asp:UpdatePanel ID="upMessages" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Label ID="lblMessage" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
Notice the Triggers section

Add ValidationControls dynamically to updatepanel? [ASP.NET]

I have a problem with my dynamic updatepanel that I've created.
The problem is that i want to add a validator,i.e RequriedFieldValidator, to every element that i'm creating on the serverside.
This above works fine.
But when i'm clicking the submit button it does nothing. I can see in the htmlShellcode that a span element is there showing the error, but it has the "style="visibility=hidden".
How do i solve this issue? i'm not really sure i'm doing it right from the beginning either(very new to programming).
MARKUP:
<asp:Panel ID="UpdatepanelWrapper" CssClass="Updatepanelwrapper" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="WholeWrapper">
<asp:PlaceHolder runat="server" ID="QuestionWrapper">
<asp:PlaceHolder runat="server" ID="LabelQuestion"><asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="Question"></asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel ID="ButtonPanel" CssClass="ButtonPanel" runat="server">
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/Images/Deleteicon.png" CssClass="DeleteButton" OnClientClick="btnDelete_Click" />
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Addicon.png" CssClass="AddButton" OnClientClick="btnAddQuestion_Click" />
</asp:Panel>
</asp:Panel>
SERVERSIDE CODE: (Override method OnInit is the important one)
public partial class _Default : Page
{
static int CountOfQuestions = 1;
private RequiredFieldValidator[] ArrRequiredFieldQuestion;
private Panel[] ArrWholePanel;
private Panel[] ArrQuestionPanel;
private Label[] ArrQuestionLabel;
private TextBox[] ArrQuestionBox;
protected void Page_Load(object sender, EventArgs e)
{
}
private void LoadControls()
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAdd") //Ändra till btnAddQuestion om en "button" ska användas
{
CountOfQuestions++;
}
if (myControl.ID.ToString() == "btnDelete")
{
CountOfQuestions--;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsPostBack)
{
CountOfQuestions = 1;
}
LoadControls();
ArrRequiredFieldQuestion = new RequiredFieldValidator[CountOfQuestions];
ArrWholePanel = new Panel[CountOfQuestions];
ArrQuestionPanel = new Panel[CountOfQuestions];
ArrQuestionLabel = new Label[CountOfQuestions];
ArrQuestionBox = new TextBox[CountOfQuestions];
for (int i = 0; i < CountOfQuestions; i++)
{
RequiredFieldValidator ReqFieldQuestion = new RequiredFieldValidator();
PlaceHolder WholeWrapper = UpdatePanel1.FindControl("WholeWrapper") as PlaceHolder;
Panel WholePanel = new Panel();
Panel QuestionPanel = new Panel();
Panel CorrectAnswerPanel = new Panel();
Label QuestionLabel = new Label();
TextBox Question = new TextBox();
QuestionLabel.Text = "Write your question";
Question.TextMode = TextBoxMode.MultiLine;
Question.Width = 550;
Question.Height = 50;
WholePanel.ID = "WholePanel" + i.ToString();
QuestionPanel.ID = "QuestionPanel" + i.ToString();
Question.ID = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ID = "Validate" + i.ToString();
ReqFieldQuestion.ControlToValidate = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ValidationGroup = "QuestionGroup";
ReqFieldQuestion.ErrorMessage = "Error";
ReqFieldQuestion.Attributes.Add("runat", "server");
QuestionPanel.CssClass = "QuestionEntry";
QuestionPanel.Controls.Add(QuestionLabel);
QuestionPanel.Controls.Add(Question);
QuestionPanel.Controls.Add(ReqFieldQuestion);
WholeWrapper.Controls.Add(WholePanel);
WholePanel.Controls.Add(QuestionPanel);
ArrRequiredFieldQuestion[i] = ReqFieldQuestion;
ArrQuestionPanel[i] = QuestionPanel;
ArrQuestionLabel[i] = QuestionLabel;
ArrQuestionBox[i] = Question;
}
}
protected void btnAddQuestion_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
public static Control GetPostBackControl(Page thePage)
{
Control postbackControlInstance = null;
if (postbackControlInstance == null)
{
for (int i = 0; i < thePage.Request.Form.Count; i++)
{
if ((thePage.Request.Form.Keys[i].EndsWith(".x")) || (thePage.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = thePage.FindControl(thePage.Request.Form.Keys[i].Substring(0, thePage.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}
return postbackControlInstance;
}
But when i'm clicking the submit button it does nothing.
Since I don't see a Submit button, I'm taking a guess that you mean the Add and Remove buttons. If this is the case, the problem is that all your RequiredFieldValidators have the ValidationGroup property set to QuestionGroup but this is not set in any of your buttons.
Modify the Buttons like this:
<asp:ImageButton ID="btnAdd" runat="server" ValidationGroup="QuestionGroup" ... />

When I click on submit button no function is called

in my website when I click a submit button it should show all the links in a textbox ,but my submit button is not working, noting happens when I click it. Here's my code. My submit button has onclient click property.
protected void btnRender_Click(object sender, EventArgs e)
{
string strResult = string.Empty;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url.Text);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
strResult = sr.ReadToEnd();
sr.Close();
}
strResult = strResult.Replace("<form id='form1' method='post' action=''>", "");
strResult = strResult.Replace("</form>", "");
//strResult = strResult.Replace("<!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">");
div.InnerHtml = strResult;
}
protected void btn_createlink_Click(object sender, EventArgs e)
{
var links = TextBox1.Text.Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var link in links)
{
if (!IsLinkWorking(link))
{
//Here you can show the error. You don't specify how you want to show it.
TextBox2.Text += string.Format("{0}\nNot working\n\n ", link);
}
else
{
TextBox2.Text += string.Format("{0}\n working\n\n", link);
}
}
}
bool IsLinkWorking(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
//You can set some parameters in the "request" object...
request.AllowAutoRedirect = true;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return true;
}
catch
{
//TODO: Check for the right exception here
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
url.Text = "";
}
}
here is my client side code
here i have function called finda() .when client clicks on submit button it should call but this not happening
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript">
function finda() {
var a = document.getElementsByTagName("a");
var b = document.getElementById("TextBox1");
b.value = "";
for (var i = 0; i < a.length; i++) {
a[i] = a.length.value;
if (a[i] == null) {
alert("Their is no links");
}
else {
b.value = b.value + "\r\n\n" + a[i];
}
}
// window.open("http://www.fillsim.com");
window.close();
// window.open("WebForm3.aspx?req=" + b.value);
}
</script>
<script type = "text/javascript">
var defaultText = "http://www.example.com";
function waterMarkText(txt, evt) {
if (txt.value.length == 0 && evt.type == "blur") {
txt.style.color = "red";
txt.value = defaultText;
}
if (txt.value == defaultText && evt.type == "focus") {
txt.style.color = "green";
txt.value = "";
}
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" >
Enter the URL:<br />
<br />
<asp:TextBox ID="url" runat="server" Width="263px"></asp:TextBox>
<br />
<br />
<asp:Button ID="btnRender" runat="server" Text="Page Render" OnClick="btnRender_Click" />
<asp:Button ID="btn_submit" runat="server" Text="Submit" OnClientClick="javascript:finda();" />
<asp:Button ID="btn_createlink" runat="server"
Text="Create link" OnClick="btn_createlink_Click" />
<asp:TextBox ID="TextBox2" runat="server" Height="371px" TextMode="MultiLine" Width="409px"></asp:TextBox>
<div class="ab" id="div" runat="server">
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Clear"
Width="71px" />
</div>
</form>
Your form tag should have runat="server" attribute so that ASP.NET postback events can be properly handled.

Ajax Timer: Execute only 5 times

I have a ajax Timer control. It adds “+” to the text value of a label. This timer should work only five times with an interval of “1000” – i.e, only five “+” should be available. After that, the lblPostbackType
Should be updated with the count. How do I achieve it?
public partial class _Default : System.Web.UI.Page
{
static int partialPostBackCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
partialPostBackCount = partialPostBackCount + 1;
lblPostbackType.Text = "Partial Postback:: " + partialPostBackCount.ToString();
}
else
{
lblPostbackType.Text = "Full Postback";
}
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = Label1.Text + "+";
}
}
And the designer code is
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="Timer1" Interval="1000" OnTick="Timer1_Tick" />
<asp:Label runat="server" ID="lblPostbackType" >SAMPLE</asp:Label>
<asp:UpdatePanel runat="server" ID="TimePanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="Label1" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks
try this
protected void Timer1_Tick(object sender, EventArgs e)
{
if (partialPostBackCount > 5 )
{
lblPostbackType.Text = "Partial Postback:: " +
partialPostBackCount.ToString();
//Timer1.Enabled = false; //if you don't want it to continue
}
else
{
partialPostBackCount = partialPostBackCount + 1;
Label1.Text = Label1.Text + "+";
}
}
*static variables are not recommended..
keep the Page_Load event method clean..

Categories

Resources