See the Image below:
Scenario
I have a repeater control bearing Id "rpt1" ,inside the ItemTemplate of which I have a span control whose Id is "abc", which is currently displaying a number. I also have a ticker above the repeater in format dd-MM-yyyy hh:mm:ss (27-05-2013 11:24:36), made up of ASP:Timer and ASP:UpdatePanel.
Requirement
What i need is that whenever my second part of the timer reaches 00, I would like to change the content of span from number to some image.
Code
ASPX:
<form id="form1" runat="server">
<asp:ScriptManager ID="scr" runat="server">
</asp:ScriptManager>
<asp:Timer ID="timer" runat="server" Interval="1000" OnTick="timer_Tick">
</asp:Timer>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Always">
<ContentTemplate>
<asp:Label runat="server" ID="lblNum"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:Repeater runat="server" ID="rpt1">
<ItemTemplate>
<table>
<tr>
<td>
<span id="abc" runat="server">
<%#Eval("Number") %></span>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</form>
CS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Threading;
namespace WebTest
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindList();
}
protected void timer_Tick(object sender, EventArgs e)
{
lblNum.Text = string.Format("{0:dd:MM:yyyy hh:mm:ss}",DateTime.Now);
if (DateTime.Now.Second == 30)
{
Thread t = new Thread(DisplayImages);
t.Start();
t.Suspend();
t.Join();
}
}
private void BindList()
{
var list = new List<Numbers>();
list.Add(new Numbers() { Number = 5 });
list.Add(new Numbers() { Number = 6 });
list.Add(new Numbers() { Number = 7 });
list.Add( new Numbers() { Number = 5 });
list.Add(new Numbers() { Number = 5 });
rpt1.DataSource = list;
rpt1.DataBind();
}
private void DisplayImages()
{
foreach (RepeaterItem item in rpt1.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
var checkBox = ((HtmlGenericControl)(item.FindControl("abc")));
checkBox.InnerHtml = "<img src='http://pra.aps.org/sites/pra.test.ridge.aps.org/themes/PRA/graphics/button_go.gif'/>";
}
}
}
}
public class Numbers
{
public int Number { get; set; }
}
}
Earlier the code was executing on single thread. Now, I tried keeping the threads apart but no avail. I think reloading page each time is main issue. Is it possible that I can only refresh the timer part not the entire page.
All you have to do is:
In the ASPX code, move the REPEATER into the UpdatePanel.ContentTemplate, juste below lblNum.
In the C# code, remove the line "t.Suspend();".
I hope this will help you.
CODE
ASPX:
<form id="form1" runat="server">
<asp:ScriptManager ID="scr" runat="server">
</asp:ScriptManager>
<asp:Timer ID="timer" runat="server" Interval="1000" OnTick="timer_Tick">
</asp:Timer>
<asp:UpdatePanel runat="server" ID="up1" UpdateMode="Always">
<ContentTemplate>
<asp:Label runat="server" ID="lblNum"></asp:Label>
<asp:Repeater runat="server" ID="rpt1">
<ItemTemplate>
<table>
<tr>
<td>
<span id="abc" runat="server">
<%#Eval("Number") %>
</span>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="timer" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
CS:
protected void timer_Tick(object sender, EventArgs e)
{
lblNum.Text = string.Format("{0:dd:MM:yyyy hh:mm:ss}", DateTime.Now);
if (DateTime.Now.Second == 30)
{
Thread t = new Thread(DisplayImages);
t.Start();
//t.Suspend();
t.Join();
}
}
Related
I'm hoping someone can help me as I'm beating my head against a wall trying to figure out the problem. I have a databound CheckboxList that has the SelectedIndexChanged event wired up. AutoPostBack is equal to true and ViewStateMode and EnableViewState are set to "Enabled" and "True" respectively. I have other controls on this same page with server side events that fire just fine with no issue.
The weird thing is, the event SEEMS to be firing, as I can see the page reload when I check one of the items in the list. However, when I set a debug point on the method, the debugger never breaks into that section and none of my code is firing (I've even tried having it write out silly messages just to see if the method is even firing - it's not). Here's the markup:
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
Here's the SelectedIndexChanged event:
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
//Do all the things
}
What am I missing? I feel like it must be something obvious but for the life of me, I can't see it.
Also I should note this is in the latest version of Mono so there might be some weird quirk there that's causing the issue.
One final note, there are no errors in the console if I check the browser developer tools so I don't have any weird javascript stuff going on that's causing an issue.
Update
Since it's been asked, I'm posting the entire page markup and the requisite codebehind.
Markup:
<%# Page Language="C#" MasterPageFile="~/pages/master/main.master" Inherits="Letters.Web.UI.searchLetters" AutoEventWireup="true" %>
<asp:Content runat="server" ContentPlaceHolderID="additionalCSS">
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/letters.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/font-awesome.min.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap.css") %>" />
<link rel="stylesheet" type="text/css" href="<%= Page.ResolveClientUrl("~/resources/css/bootstrap-multiselect.css") %>" />
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="additionalJS">
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap.min.js") %>">
</script>
<script type="text/javascript"
src="<%= Page.ResolveClientUrl("~/resources/javascript/bootstrap-multiselect.js") %>">
</script>
</asp:Content>
<asp:Content runat="server" ContentPlaceHolderID="mainContent">
<section id="search-header">
<div class="column">
<div class="field-set">
<asp:Label id="lblTextString" runat="server" CssClass="data-label">Search for Letters</asp:Label>
<div class="data-control">
<asp:TextBox id="txtTextString" Width="100%" runat="server" CssClass="form-control searchable" placeholder="Contains Text" data-paramname="textString" />
</div>
</div>
</div>
<div class="column-small">
<div class="field-set">
<span class="data-label"> </span>
<div class="data-control">
<button id="btnSearch" runat="server" class="search-nav-buttons" onserverclick="Search_Click">
Search
</button>
</div>
</div>
</div>
</section>
<asp:PlaceHolder id="plcSearchResults" runat="server">
<section id="search-results">
<div class="filter-options">
<table>
<tbody>
<tr class="searchresults-headerstyle">
<th scope="col" class="header">Filter Options</th>
</tr>
</tbody>
</table>
<asp:Panel id="pnlLanguage" runat="server">
<h1>Languages</h1>
<asp:HiddenField id="hdlLanguages" runat="server" />
<asp:CheckBoxList id="chkLanguages" runat="server" AutoPostBack="true" ViewStateMode="Enabled" EnableViewState="true" data-paramname="lcid"
OnSelectedIndexChanged="chkLanguages_SelectedIndexChanged" />
</asp:Panel>
</div>
<asp:GridView id="grvResults" runat="server" CssClass="table table-striped table-bordered" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" Width="70%" GridLines="None"
OnPageIndexChanging="GridView_PageIndexChanging" >
<HeaderStyle CssClass="searchresults-headerstyle" />
<FooterStyle CssClass="searchresults-footerstyle" />
<PagerStyle CssClass="pagination-style" />
<Columns>
<asp:TemplateField HeaderText="Search Results" >
<ItemTemplate>
<div class="search-result-record">
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("LetterUrl") %>' Text='<%# Letters.Tools.WebUtils.HtmlEncode(Eval("Title").ToString()) %>' />
<span>(<%# Eval("Language") %>)</span>
<span class="keywords">Keywords: <%# Eval("Categories") %></span>
<asp:Label runat="server" CssClss="language" Visible='<%# Eval("LCID").ToString() != "en" %>'>Language: <%# Eval("Language") %></asp:Label>
<div class="search-abstract">
<%# Eval("SearchAbstract") %>
</div>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</section>
</asp:PlaceHolder>
</asp:Content>
Code Behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Letters.Domain.Objects;
using Letters.Tools;
namespace Letters.Web.UI
{
public partial class searchLetters : System.Web.UI.Page
{
#region eventhandlers
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack) {
this.BindResults ();
}
}
protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grvResults.PageIndex = e.NewPageIndex;
this.BindResults ();
}
protected void chkLanguages_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.chkLanguages);
this.FilterResults ();
}
protected void Search_Click(object sender, EventArgs e)
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
#endregion
private void FilterResults()
{
Dictionary<string, object> parameters = new Dictionary<string, object> ();
if (pnlLanguage.Visible) {
parameters.Add (this.chkLanguages.Attributes ["data-paramname"].ToString (), this.GetSelectedItems (this.chkLanguages));
}
//Finally, add the search string
if (!string.IsNullOrEmpty (this.txtTextString.Text))
parameters.Add (this.txtTextString.Attributes ["data-paramname"].ToString (), this.txtTextString.Text);
this.BindResults (parameters);
}
private string[] GetFilterOption(string delimitedValue)
{
string[] result = null;
if (delimitedValue.Contains (",")) {
result = delimitedValue.Split (new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
} else
result = new string[] { delimitedValue };
return result;
}
private string GetSelectedItems(CheckBoxList list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private string GetSelectedItems(ListBox list)
{
StringBuilder result = new StringBuilder ();
foreach (ListItem item in list.Items) {
if (item.Selected)
result.Append (item.Value).Append (",");
}
if (result.Length > 0) {
result.Remove (result.Length - 1, 1);
return result.ToString ();
}
else
return null;
}
private void PopulateFilters(List<SearchResult> results)
{
var languages = (from x in results
group x by new { x.LCID, x.Language } into counts
select new { Key = counts.Key.LCID, DisplayName = string.Format("{0} ({1})", counts.Key.Language, counts.Count()) }
).ToList();
this.chkLanguages.DataSource = languages;
this.chkLanguages.DataTextField = "DisplayName";
this.chkLanguages.DataValueField = "Key";
this.chkLanguages.DataBind ();
if (!string.IsNullOrEmpty (hdlLanguages.Value)) {
string[] languageSelect = this.GetFilterOption (hdlLanguages.Value);
foreach (ListItem item in this.chkLanguages.Items) {
if (languageSelect.Contains (item.Value))
item.Selected = true;
}
}
}
private void BindResults()
{
List<SearchResult> results = this.GetSearchResults ();
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void BindResults(Dictionary<string, object> parameters)
{
List<SearchResult> results = this.GetSearchResults(parameters);
this.grvResults.DataSource = results;
this.grvResults.DataBind ();
this.PopulateFilters (results);
}
private void RegisterEvents()
{
this.grvResults.PageIndexChanging += new System.Web.UI.WebControls.GridViewPageEventHandler (GridView_PageIndexChanging);
}
private List<SearchResult> GetSearchResults()
{
return LetterService.GetSearchResults ();
}
private List<SearchResult> GetSearchResults(Dictionary<string, object> parameters)
{
return LetterService.GetSearchResults (parameters);
}
}
}
I was never able to find the exact cause to the problem. Every other type of control was able to post back events and I could properly handle their events server-side. I ended up working around this particular issue by ripping out the CheckBoxList and replacing it with a gridview that used an item template to store the value in a hidden field and display the checkbox where I could then handle the OnCheckedChanged event (see code below). This worked brilliantly.
Markup
<asp:GridView id="grvLanguages" runat="server" ShowHeader="false" ShowFooter="false" AllowPaging="false"
AllowSorting="false" GridLines="None" AutoGenerateColumns="false" data-paramname="languages" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField id="hdlValue" runat="server" Value='<%# Eval("Key") %>' />
<asp:CheckBox id="chkDisplay" runat="server" Text='<%# Eval("DisplayName") %>' OnCheckedChanged="chkLanguage_SelectedIndexChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code Behind
protected void chkLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
this.hdlLanguages.Value = this.GetSelectedItems (this.grvLanguages);
this.FilterResults ();
}
I'm guessing the problem is probably some weird, esoteric bug in the Mono framework. Like I said, I don't have a problem with ANY other controls (I tested quite a few - all of their server side events handled just fine); it was just a problem with the CheckBoxList.
I'm trying to update the source of an iFrame when a button is clicked on the page. However, nothing seems to be happening...
.ASPX:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0"></iframe>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
protected void SubmitSponsor(object sender, EventArgs e)
{
var driver = new Driver();
var isvalid = driver.IsAppValid(URL.Text, APILINK, Connstring);
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.google.com");
URLInvalid.Visible = false;
}
}
I've also tried:
PayPalFrame.Attributes["src"] = "http://www.google.com"; and still nothing.
I have tested your code, and it works in a sample project:
ASPX:
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="accountInfo">
<p class="submitButton">
<asp:Button ID="ValidateButton" runat="server" Text="Validate" OnClick="SubmitSponsor" />
</p>
</div>
<iframe runat="server" id="PayPalFrame" height="150px" width="100%" frameborder="0">
</iframe>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Codebehind:
public partial class UpdatePanelIFrameTester : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitSponsor(object sender, EventArgs e)
{
bool isvalid = true;
if (isvalid)
{
PayPalFrame.Attributes.Add("src", "http://www.ironworks.com");
}
}
}
I would inspect your code and ensure nothing is causing your page to refresh/perform a full postback (I changed the URL as google will not allow you to view it in an iframe under standard conditions).
I believe you have to remove the src attribute and then re-add it, for this to work. Not sure why this is, but I remember doing it the last time I worked with update panels. Perhaps it's because the src attribute always already exists?
Anyway, here's some sample code: how to change the src attribute in iframe.
Here's the problem:
I have a control (A) that I register/load into another control (B). then I register control (B) into a normal .aspx page
I put a 'Script Manager' in this page and I use ajax 'Update Panel' in both controls but only the main components of the control (B) works (excluding the control (A) which I registered into control (B)) .. so basically the ajax part works for the component that's loaded into a page. if it's loaded into another control it won't work!
I wanted to make sure that it's not a silly mistake in my code so I copied the code of the control that's not working and added it to a normal page and it worked!
so what do you think the problem is or can I do about it !?
EDIT Some Code
Control (B) :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Itinerary.ascx.cs" Inherits="OTV.controls.Itinerary.ItineraryControl" %>
<p>
Add new itinerary:</p>
<p>
<br />
</p>
<div id="newItinerary_div" runat="server">
<p>
Title:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
Description:
<asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine"></asp:TextBox>
Visible:
<asp:CheckBox ID="CheckBox1" runat="server" />
<div id="itineraryDays_div" runat="server">
<h4>Itinerary days:</h4>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder ID="DaysHolder" runat="server"></asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="addMoreDay_btn" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="addMoreDay_btn" runat="server" Text="Add one more day"
onclick="addMoreDay_btn_Click" />
This button dynamically create itineraryDay controller to the div
</div>
</div>
</div>
Control (B) - Code Behind File:
public partial class ItineraryControl: System.Web.UI.UserControl
{
static int DaysCount = 1;
static List<Control> _daysList;
protected void addMoreDay_btn_Click(object sender, EventArgs e)
{
}
public static Control GetPostBackControl(Page thePage)
{
Control myControl = null;
string ctrlName = thePage.Request.Params.Get("__EVENTTARGET");
if (((ctrlName != null) & (ctrlName != string.Empty)))
{
myControl = thePage.FindControl(ctrlName);
}
else
{
foreach (string Item in thePage.Request.Form)
{
Control c = thePage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
myControl = c;
}
}
}
return myControl;
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if ((myControl != null))
{
if ((myControl.ClientID.ToString() == "addMoreDay_btn"))
{
DaysCount = DaysCount + 1;
}
}
_daysList = new List<Control>();
for (int i = 1; i <= DaysCount; i++)
{
Control OneMoreDay = LoadControl("~/controls/Itinerary/ItineraryDayAdd.ascx");
OneMoreDay.ID = "dayNo" + i;
(OneMoreDay.FindControl("DayNum_TxtBx") as TextBox).Text = i.ToString();
DaysHolder.Controls.Add(OneMoreDay);
_daysList.Add(OneMoreDay);
}
}
}
}
Control (A) :
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ItineraryDayAdd.ascx.cs" Inherits="OnlineTravelAgency1.controls.Itinerary.ItineraryDayAdd" %>
<p>
Day#:
<asp:TextBox ID="DayNum_TxtBx" runat="server"></asp:TextBox>
</p>
<p>
Title:
<asp:TextBox ID="Title_TxtBx" runat="server"></asp:TextBox>
</p>
<p>
Day:
<asp:DropDownList ID="Days_DrpDwnLst" runat="server">
<asp:ListItem Value="0">Saturday</asp:ListItem>
<asp:ListItem Value="1">Sunday</asp:ListItem>
<asp:ListItem Value="2">Monday</asp:ListItem>
<asp:ListItem Value="3">Tuesday</asp:ListItem>
<asp:ListItem Value="4">Wednesday</asp:ListItem>
<asp:ListItem Value="5">Thursday</asp:ListItem>
<asp:ListItem Value="6">Friday</asp:ListItem>
</asp:DropDownList>
</p>
<p>
Description:
<asp:TextBox ID="TextBox2" runat="server" TextMode="MultiLine"></asp:TextBox>
</p>
...This is my whole code! I'm really stuck and I didn't want to overwhelm you with my code but I can't help you enough to understand my problem
I have found many solution for my issue but none doesn't work in my scenario.
I have created a test project to demo my concept.
Basically, there is a page that host a user control...
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
WebUserControl1 has a dropdownlist and two other webusercontrols (to be displayed based on the selection of dropdownlist element) inside updatepanel as below.
<%# Register Src="WebUserControl2.ascx" TagName="WebUserControl2" TagPrefix="uc2" %>
<%# Register Src="WebUserControl3.ascx" TagName="WebUserControl3" TagPrefix="uc3" %>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
</asp:DropDownList>
<asp:Panel ID="pnlCreditCard" Visible="false" runat="server">
<uc2:WebUserControl2 ID="WebUserControl21" runat="server" />
</asp:Panel>
<asp:Panel ID="pnlGiftCard" Visible="false" runat="server">
<uc3:WebUserControl3 ID="WebUserControl31" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
Code behind file for WebUserControl1 is .....
public enum PaymentMethod
{
CreditCard = 0,
GiftCard
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindPaymentMethods(Enum.GetValues(typeof(PaymentMethod)));
}
private void BindPaymentMethods(Array paymentMethods)
{
DropDownList1.DataSource = paymentMethods;
DropDownList1.DataBind();
if (paymentMethods.Length > 0)
{
DropDownList1.SelectedIndex = 0;
UpdateCreditOrGiftCardPanelVisibility();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateCreditOrGiftCardPanelVisibility();
}
private void UpdateCreditOrGiftCardPanelVisibility()
{
if(DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod),PaymentMethod.CreditCard))
{
pnlGiftCard.Visible = false;
pnlCreditCard.Visible = true;
}
else if (DropDownList1.SelectedValue == Enum.GetName(typeof(PaymentMethod), PaymentMethod.GiftCard))
{
pnlCreditCard.Visible = false;
pnlGiftCard.Visible = true;
}
}
Now, the problem starts here...There is an external javascript file [JScript1.js] (embedded resource) which basically is used to display an alert box.
<script language="javascript" type="text/javascript">
window.onload = function() {
alert('creditcard form');
}
WebUserControl2.ascx.cs code behind is
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptInclude(this.Page, this.Page.GetType().BaseType, "JScript1", Page.ClientScript.GetWebResourceUrl(this.Page.GetType().BaseType, "WebApplication1.JScript1.js"));
}
Alert window doesn't get displayed when I change the dropdownlist value. Even the script is getting registered three times (look in the firebug)
Need to use ScriptInclude instead of ScriptBlock as the original JS file is too big.
Can email the test app....
Thanks in Advance
After working around a bit, I found the solution.
I registered a ScriptManagerProxy in WebUserControl2.ascx
<asp:ScriptManagerProxy ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Assembly="WebApplication1" Name="WebApplication1.JScript1.js" />
</Scripts>
</asp:ScriptManagerProxy>
Then on the code behind of the same control, added...
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
ScriptManager.RegisterStartupScript(this, GetType(), "test", "doSomething();", true);
}
and the JScript1.js file looks like below.
function doSomething() {
alert('via dosomething control2 form');
}
Hope that helps. Though I had to litter around more in my practical scenario but this was certainly the way I got it working.
Thanks,
I have an ASP .NET page with both asp .net validators and some javascript checking too.
I am advancing into the button code behind:
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
/// ...
Even when the validation fails!
The Page.IsValid check solves it, but it also resets all the JavaScript variables… May there be a way not to advance into the button code?
I have an ajax update panel and some image buttons on the page too… Anything I may look out for?
Thanks in advance!
Here is my aspx:
<%# Page Language="C#" AutoEventWireup="true"
CodeBehind="WebForm2.aspx.cs"
Inherits="WebForm2" %>
<!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">
<div style="width: 500px;">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script type="text/javascript">
var nrOptions = 0;
alert(nrOptions + " - variable initialized");
function IncrementQuantity() {
nrOptions++;
alert(nrOptions);
}
function DecrementQuantity() {
nrOptions--;
alert(nrOptions);
}
function MoreThanTwo() {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
return true;
}
else {
alert('error - must have at least two options, you only have: ' + nrOptions);
return false;
}
}
</script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<HeaderTemplate>
Fill in with two or more options:<br />
<table border="1" width="100%">
</HeaderTemplate>
<ItemTemplate>
<tr>
<td valign="middle">
</td>
<td valign="middle">
Description:
<asp:TextBox ID="TBox1" runat="server" Width="120px" Text='<%# Eval("Desc")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TBox1"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
Points:
<asp:TextBox ID="TBox2" runat="server" Width="20px" Text='<%# Eval("Pont")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="TBox2"
ValidationGroup="InsertVal" ErrorMessage="*"></asp:RequiredFieldValidator>
<asp:Button ID="ImageButton1" runat="server" Text="x" CommandName="DeleteRow" OnClientClick="DecrementQuantity();" />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ControlToValidate="TBox2"
ValidationExpression="\d+" ValidationGroup="InsertVal" runat="server"
ErrorMessage="Number >= 0."></asp:RegularExpressionValidator>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td colspan="2" align="right">
<asp:Button ID="lnkAddRow" runat="server" Text="Add option" OnClientClick="IncrementQuantity();"
CommandName="AddRow" OnClick="lnkAddRow_Click" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<p style="text-align: right;">
<asp:Button ID="Button2" runat="server" Text="Save" OnClick="Button2_Click" OnClientClick="return MoreThanTwo();"
ValidationGroup="InsertVal" />
</p>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
And my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DTable = EmptyDTOptions();
Repeater1.DataSource = DTable;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "AddRow")
{
DTable.Rows.Add(0, "", "");
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
if (e.CommandName == "DeleteRow")
{
int idx = e.Item.ItemIndex;
DTable.Rows.RemoveAt(idx);
Repeater1.DataSource = DTable;
Repeater1.DataBind();
return;
}
}
protected void lnkAddRow_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
int idx = item.ItemIndex;
TextBox tb1 = (TextBox)item.FindControl("TBox1");
TextBox tb2 = (TextBox)item.FindControl("TBox2");
DTable.Rows[idx]["Desc"] = tb1.Text;
DTable.Rows[idx]["Pont"] = tb2.Text;
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
// save!
}
}
private DataTable DTable
{
get
{
DataTable _dt = (DataTable)Session["DTable"];
if (Object.Equals(_dt, null))
{
_dt = EmptyDTOptions();
Session.Add("DTable", _dt);
}
return _dt;
}
set
{
Session["DTable"] = value;
}
}
DataTable EmptyDTOptions()
{
DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn("OptionNr", System.Type.GetType("System.Int32"));
dt.Columns.Add(dc);
dc = new DataColumn("Desc");
dt.Columns.Add(dc);
dc = new DataColumn("Pont");
dt.Columns.Add(dc);
return dt;
}
}
I think it shows what I'm trying to avoid... Advancing to the button2_click with the failed validation (and resetting the javascript variable)... In order to get a list of two or more pairs of items, one of them being a number.
Rather than calling your function from the OnClientClick on the button, you can add a CustomValidator that calls your JavaScript function.
<asp:CustomValidator ID="CheckMoreThanTwo" runat="server"
ValidationGroup="InsertVal"
ClientValidationFunction="MoreThanTwo" />
Then, modify your JavaScript function as follows:
function MoreThanTwo(source, arguments) {
alert(nrOptions);
if (nrOptions > 1) {
alert('okay - you have: ' + nrOptions);
arguments.IsValid=true;
} else {
alert('error - must have at least two options, you only have: '
+ nrOptions);
arguments.IsValid=false;
}
}
Doing this allows your custom JavaScript validation to work with all the validation code that ASP.NET uses. For instance, if you change to a validation summary, or change validation groups, this custom validator will continue to work the way the rest of the validators work.