Running a C# and a Javascript function on an asp button control? - c#

I can get both the Javascript and the C# function to work just fine.
However, my Javascript function runs before the C#.
How do I get it to run after the C# function??
Here is my code:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"
OnClientClick="javascript:Highlit()" />
</div>
</asp:View>
</asp:MultiView>
<script type="text/javascript">
function Highlit()
{
$("#div2").effect("highlight", {}, 10000);
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
Code behind:
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
}
}
}
Here is the code reflecting changes from the answers:
Code behind
namespace jQuery_Highlight.jQuery_Highlight
{
public partial class jQuery_HighlightUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "TEST", "Highlit();", true);
}
}
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div id="div2" style="height:70px; width:auto; text-align:center;">
<p><b>This is A View!!!</b></p>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div id="div1">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</asp:View>
</asp:MultiView>
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
function Highlit() {
$("#div2").effect("highlight", { color: "#9499FC" }, 10000);
}
</script>

The only way to get the javascript to run after is to add a script reference in your Button1_Click event.
Example Code for standard postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}
As noted by others, be sure to remove your OnClientClick event. Also, consider moving your "Highlit" script outside of the update panel.
Additionally, since you are in an update panel, you will need to use the following example code for a Partial Postback:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Changed";
ScriptManager.RegisterStartupScript(this, this.GetType(), "PostButton1_ClickScript", "Highlit();", true);
}

You have to register a ClientScript at the end of Button1_Click event
and remove OnClientClick="javascript:Highlit()"
protected void Button1_Click(object sender, EventArgs e)
{
//Do stuff
ScriptManager.RegisterStartupScript(this, this.GetType(), "ANYNAME", "javascript:Highlit();", true);
}

Remove the OnClientClick attribute, and add the call as a startup script, so that it runs after the page has loaded:
protected void Button1_Click(object sender, EventArgs e) {
Label1.Text = "Changed";
Page.ClientScript.RegisterStartupScript(this.GetType(), "start", "Highlit();", true);
}
Side note: When you use the OnClientClick attribute, the code should not start with javascript:. That's only used when you put script in a href attribute in a link.

Related

Cannot put the text in input box in asp.net

I am trying to make the input box show some text in the asp.net using c#, but after I run the code behind, nothing is displayed in the input box. The ui is RadNumericTextBox uiDistance. In class, I put this.uiDistance.Text = "123"; But in the webpage after run the code. I cannot see "123" is put in the uiDistance text box. How can I fix it?
Here is my aspx UsageControl2SubControl1.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UsageControl2SubControl1.ascx.cs" Inherits="WebControls.UsageControl2SubControl1" %>
<asp:HiddenField ID="uiRemoved" Value="false" runat="server" />
<asp:HiddenField ID="uiID" runat="server" />
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
<div class="hr-line-dashed"></div>
And Here is my code behind: UsageControl2SubControl1.ascx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
namespace WebControls
{
public partial class UsageControl2SubControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
}
protected void uiAdd_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void uiRemove_Click(object sender, Telerik.Web.UI.ImageButtonClickEventArgs e)
{
}
protected void RadComboBoxProduct_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
}
protected void uiAdd_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiRemove_Click1(object sender, ImageClickEventArgs e)
{
}
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Text = "123";
}
}// end class
}// end namespace
Just to update your aspx code little bit
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="form-group">
<div class="col-md-2 customColumnPadding">
<telerik:RadTextBox ID="uiToLocation" runat="server" Width="100%" AutoPostBack="true"
OnTextChanged="uiToLocation_Leave" EmptyMessage="<%$ Resources:ResourceHKEx,Arrive_To %>" />
</div>
<div class="col-md-2 customColumnPadding" id="uiColumnDistance" runat="server">
<telerik:RadNumericTextBox ID="uiDistance" runat="server" Width="100%" MinValue="0" NumberFormat-DecimalDigits="2" EmptyMessage="<%$ Resources:Resource,Distance %>" />
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
As your textbox is only inside the update panel so, on post back only that portion is partially updated, you need to put RadNumericTextBox inside the update panel too.
Hope this will work.
You are using the wrong property. Use Value not Text
protected void uiToLocation_Leave(object sender, EventArgs e)
{
this.uiDistance.Value = "123";
}
As always, check the documentation. See: https://docs.telerik.com/devtools/aspnet-ajax/controls/numerictextbox/features/getting-and-setting-values
Your current code will works only when you tab out from uiToLocation textbox.
If you want to show it when page loads, just move your code in to Page_Load event instead uiToLocation_Leave.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
this.uiDistance.Text = "123"; // it will assign when page loads.
}
If you want to load it only once when page loads, use IsPostaback, see below.
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToBoolean(uiRemoved.Value))
{
this.Visible = false;
}
if (!IsPostBack)
{
this.uiDistance.Text = "123"; // it will assign only once when page loads.
}
}
IT seems you are using the wrong property to assign value to telerik Textbox.
Use .Value property as .Text property if for default aspx Textbox control
this.uiDistance.Value= "123"

Timer in ASP.Net (Language C#) stops after 1 tick

i wanted to use a timer in a program i'm working on, but it always stops after 1 tick !! can you give me any tips to make it repeat unstoppably (or until i want it to) please ??
this is my code:
int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = "(" + i + ")";
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
Edit: my HTML code :
<form id="form1" runat="server">
<div><center>
<span class="style1">message</span><br
class="style1" />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick" >
</asp:Timer>
<asp:Timer ID="Timer2" runat="server" Interval="1000">
</asp:Timer>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"
PostBackUrl="~/Acceuil.aspx">Retour</asp:LinkButton>
<br />
</center>
</div>
</form>
Edit2: what i want to do is the normal redirecting code, count to 20 and refreshing every second (to show to user how much secs left) and at the end it redirects to a new page, but it wasn't working, so i was wondering why ??
and i think i got my answer from #Andrei Rînea, and thank you everyone for your help : )
Edit3: Solved and here is the code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "20";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text = i.ToString();
if (i == 0)
{
i = 20;
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
Thanks everyone again : )
Please use the following code :
static int i = 20;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
Label1.Text = "(20)";
}
protected void Timer1_Tick(object sender, EventArgs e)
{
i--;
Label1.Text =i.ToString();
if (i == 0)
{
Session["Profession"] = "Visiteur";
Response.Redirect("Acceuil.aspx");
}
}
your HTML code should be like :
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Timer ID="Timer1" runat="server" ontick="Timer1_Tick" Interval="1000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I'm going to assume here that you are wishing to have a process that ticks away on your server in the background.
I'm also going to assume you've tried to add this to your Webform.
If so, the issue you have encountered, is that your Webform object only exists for the short time that it is processing your request, after which it is disposed of - including your timer.
If I'm correct, you'd probably like to take a look at Quartz.Net:
http://www.mikesdotnetting.com/article/254/scheduled-tasks-in-asp-net-with-quartz-net
You are trying to run client side code on the server. You need to do this in JavaScript instead.
The C# code will be run just before rendering the page and not longer. You probably believe the code will run as long as the visitor is on the page which is not the case.

How to access to variable in ASPX page?

ASPX:
<form id="form1" runat="server">
<%
int a = 25;
%>
<asp:Label ID="Label1" runat="server"
Text='<%#a %>'></asp:Label>
</form>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataBind();
}
}
Error:
The name 'a' does not exist in the current context
Found solution:
ASPX:
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server"
Text="<%#a %>"></asp:Label>
</form>
Code behind:
public int a;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
a = 25;
DataBind();
}
}
This way will work..
ASPX:
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>
code behind:
public int a;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
a = 25;
Label1.Text=a.ToString();
}
}
something to note, is that the aspx file is compiled to a class by the the System.Web.UI.Page class which implements IHttpHandler, the created class inherit the aspx.cs/aspx.vb, which explain the inherits in the <%# Page %> directive, and by logic, you cannot reference a variable declared in aspx code nugget in code behind.
As a work around, you can declare protected members in code behind and access those from code nuggets.

Disable button on update progress in ASP.net Ajax

Hi i am loading huge data by asp.net Ajax on button click in grid view showing loading message on update prgress ...in update progress time i have to disable my BtnLoadReport Button.
<td>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="updProgress"
AssociatedUpdatePanelID="UpdatePanel1"
runat="server" oninit="updProgress_Init" onprerender="updProgress_PreRender">
<ProgressTemplate>
<span style="color:green; font-style:italic;">Loading, please wait...</span>
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
<div id="DemoId">
<asp:Button ID="BtnLoadReport" runat="server" onclick="BtnLoadReport_Click"
Text="LoadReport" Width="176px" ClientIDMode="Static" OnClientClick="return clickOnLoadReport();" />
</div>
<asp:GridView ID="GridView1" runat="server" Height="170px"
onselectedindexchanged="GridView1_SelectedIndexChanged" Width="438px">
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="BtnLoadReport" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
my script to disable button
<script type="text/javascript">
var updateProgress = null;
function clickOnLoadReport() {
// This will disable all the children of the div
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack()==false) {
var nodes = document.getElementById("DemoId").getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
nodes[i].disabled = true;
// nodes[i].off("click");
}
}
}
</script>
but it is not disabling my button for long it is disabling it for just seconds
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(this.BtnLoadReport);
}
protected void BtnLoadReport_Click(object sender, EventArgs e)
{
// System.Threading.Thread.Sleep(3000);
UpdatePanel1.Update();
DataSet dataSet = new DataSet();
dataSet.ReadXml(#"C\Data.Xml");
GridView1.DataSource = dataSet.Tables[0];
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void updProgress_Init(object sender, EventArgs e)
{
BtnLoadReport.Enable = false;
}
protected void updProgress_PreRender(object sender, EventArgs e)
{
BtnLoadReport.Enable
= true;
}
this above thing i tried to disable my button BtnLoadReport on Update progress still not working
Thanks in Advance
function clickOnLoadReport() {
var requestManager = Sys.WebForms.PageRequestManager.getInstance();
requestManager.add_initializeRequest(CancelPostbackForSubsequentSubmitClicks);
function CancelPostbackForSubsequentSubmitClicks(sender, args) {
if (requestManager.get_isInAsyncPostBack() &
args.get_postBackElement().id == 'BtnLoadReport') {
args.set_cancel(true);
document.getElementById("BtnLoadReport").setAttribute("disabled", "disabled");
//alert('A previous request is still in progress that was issued on clicking ' + args.get_postBackElement().id);
}
}
}
i made changes in my javascript function it solve my problem

Cannot Unregister UpdatePanel exception with Cross Page Posting

I am getting the dreaded exception "Cannot unregister UpdatePanel with ID 'UpdatePanel' since it was not registered with the ScriptManager" when trying to combine a popup window and some Cross-Page Posting. I've been able to reproduce the problem with a small example.
I have seen other questions that handle the Unload event for the UpdatePanel, but that doesn't seem to work with the addition of the Cross Page Posting.
How do I get around this issue?
To duplicate the issue with the code below:
Start the Setup page
Press the View Popup link
Close the popup
Press the Next button to transfer to the Target page
Press the Back button to transfer to the Setup page
Press the View link and close the popup
Press the Next button, and see the failure
Here are the highlights (forgive the length, but it should be cut-and-pastable):
Setup.aspx
<head runat="server">
<title>Setup </title>
<script type="text/javascript">
function openCenteredWindow(url, height, width, name, parms) {
//Snip setting up window location stuff
var win = window.open(url, name, winParms);
return win;
}
</script>
</head>
<body>
<h1>Setup Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:TextBox ID="txtData" runat="server" Width="80%" Text="<%# Information %>" />
<br />
<asp:LinkButton ID="lbViewData" runat="server"
OnClientClick="aspnetForm.target='ViewDataPopup';"
Text="View In Popup" /> <br />
<asp:Button ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
</div>
<div>
<br />
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:updatepanel ID="UpdatePanel" runat="server" OnUnload="UpdatePanel_Unload"></asp:updatepanel>
</div>
</form>
</body>
Setup.Aspx.cs
public partial class Setup : System.Web.UI.Page
{
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (this.ViewState["Information"] != null)
_Information = this.ViewState["Information"].ToString();
}
protected override object SaveViewState()
{
this.ViewState["Information"] = _Information;
return base.SaveViewState();
}
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null && PreviousPage is TargetPage)
{
_Information = ((TargetPage)PreviousPage).SetupData;
}
else if (!Page.IsPostBack)
{
_Information = String.Format("This test started at {0}", DateTime.Now);
}
Page.DataBind();
lbViewData.PostBackUrl = "ViewData.aspx?u=0";
lbViewData.Attributes.Add("onclick", "JavaScript:openCenteredWindow(\"ViewData.aspx?u=0\", 400, 300, \"ViewDataPopup\", 'scrollbars=yes');");
}
private string _Information;
public string Information
{
get { return _Information; }
}
protected void btnNext_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/TargetPage.aspx");
}
}
ViewData.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head runat="server">
<title>View Data</title>
<script type="text/javascript">
function fixForm() {
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = "";
}
</script>
</head>
<body onload="fixForm()">
<form id="aspnetForm" runat="server">
<div>
<h2 >View Data</h2>
</div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" />
</form>
</body>
ViewData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
Setup setup = (Setup)PreviousPage;
this.SetupData = setup.Information ?? "Data not set in Setup Page";
}
Page.DataBind();
}
private string _setupData = "Did not get updated data";
protected string SetupData
{
get { return _setupData; }
set { _setupData = value; }
}
TargetPage.aspx
<%# PreviousPageType VirtualPath="~/Setup.aspx" %>
<body style="background-color: #9999BB">
<h1>Target Page</h1>
<form id="aspnetForm" runat="server">
<div>
<asp:Label ID="lblData" runat="server" Text="<%# SetupData %>" /><br />
<asp:Button ID="btnBack" runat="server" Text="Back" OnClick="btnBack_Click" />
</div>
</form>
</body>
TargetPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (this.PreviousPage == null)
Response.Redirect("Setup.aspx");
this.SetupData = PreviousPage.Information;
}
Page.DataBind();
}
public string SetupData
{
get { return ViewState["SetupData"].ToString(); }
set { ViewState["SetupData"] = value; }
}
protected void btnBack_Click(object sender, EventArgs e)
{
HttpContext.Current.Server.Transfer("~/Setup.aspx");
}
As you can see, it's enough to have the UpdatePanel just sitting on the page and doing nothing for this error to occur.

Categories

Resources