confirm Box after the Data table gets data from sql - c#

function alertbox() {
var mode = document.getElementById('<%= hdnMode.ClientID %>').value;
if (mode == "EDIT")
return false;
if (confirm("the same data is present against that ID ?") == true) {
document.getElementById('<%= hdnYesNo.ClientID %>').value = "COPY";
}
else {
document.getElementById('<%= hdnYesNo.ClientID %>').value = "CANCEL";
}
}
the above confirm message should appear after the retrieve data from sql and
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction",
"MyFunction()",true);
how to use it from codebehind and if so then how to get the return value based on the value
copy and cancel

I will try to provide an example that I just created as a testing application.
Firstly, I used the ScriptManager to apply all the javascript files that I like to be present for the web page as follows:
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="~/JS/tester.js" />
</Scripts>
</asp:ScriptManager>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Call database" />
</div>
</form>
</body>
In the <Scripts> tag add more of your JS files. This will ensure that your javascript file is added when you load the webpage.
The code that is there in my tester.js is:
function alertbox(data) {
alert("Completed the database operation with following data = " + data);
}
Now coming to your code behind scenario, what I have in my sample data is, I created a button on the webpage that would do some database operations and once completed it will alert the user about the sql update.
The button event handler is as follows:
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(2000);
int sqlReturnValue = ExecuteTheQuery();
ScriptManager.RegisterStartupScript(this, typeof(string), "Database Completed", "alertbox(" + sqlReturnValue + ");", true);
}
Now this will call the Javascript function alertbox.
(Note: this is just a small example of how you can achieve the thing that you expect)
Update:
The same can be achieved with ClientScript as well.
What I did is, add a script tag:
<head runat="server">
<title>Test Page</title>
<script src="JS/tester.js" type="text/javascript"></script>
</head>
In the code behind of the button click:
protected void Button1_Click(object sender, EventArgs e)
{
Thread.Sleep(2000);
ClientScript.RegisterStartupScript(this.GetType(), "Database Completed", "alertbox(23);", true);
}
For understanding ClientScript and ScriptManager, check this question.

Related

ASP.NET OnTextChanged method

I have ASP.NET website, there is a page when user have to enter text in textbox and image should appear depends the text that is entered. Everything is working but image appears only when you press Enter, is there a way image to appear as you entering the letters not by pressing Enter?
<asp:TextBox ID="initials" runat="server" Width="50px" OnTextChanged="initials_TextChanged" AutoPostBack="true"></asp:TextBox>
Code behind:
protected void initials_TextChanged(object sender, EventArgs e)
{
if(this.initials.Text == "A") { prvwleft.ImageUrl = "~/Images/left/A1.jpg"; }
}
In asp.net, OnTextChanged event fires when you leave the focus.
In your case, you should go for KeyDown event.
Asp.net Textbox doesn't have server side KeyDown event, so we will have to do it using jquery:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.3.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#initials').keypress(function () {
if ($(this).val() == "A") {
$('#prvwleft').ImageUrl = "~/Images/left/A1.jpg";
}
else {
$('#prvwleft').ImageUrl = "~/Images/left/A1.jpg";
}
})
});
</script>
You need to call onkeypress event in javascript like this
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript">
function tSpeedValue(txt)
{
alert("hi");
var at = txt.value;
alert(at);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" onkeypress="tSpeedValue(this)"></asp:TextBox>
</div>
</form>
</body>
</html>
and if you want to call it in server side
<asp:TextBox ID="TextBox2" runat="server" onkeypress="__doPostBack(this.name,'OnKeyPress');" ></asp:TextBox>
and in .cs page the code should be like
protected void Page_Load(object sender, EventArgs e)
{
var ctrlName = Request.Params[Page.postEventSourceID];
var args = Request.Params[Page.postEventArgumentID];
if (ctrlName == TextBox2.UniqueID && args == "OnKeyPress")
{
TextBox2_OnKeyPress(ctrlName, args);
}
}
private void TextBox2_OnKeyPress(string ctrlName, string args)
{
//your code goes here
}

How to call a javascript function before and after button click event call in asp.net

i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.

System.Web.UI.Timer Refreshes Page when Enabled

During the page_load, I disable the timer. When I pressed Button1, I enable the timer, but the page refreshes. Therefore, it never reaches the timer_tick1. I need to show a popup after a certain amount of time a button is clicked. How do I prevent the refresh from happening?
Alerts Class
public static class Alert
{
public static void Show(string message, Page page)
{
// replaces the quotations to follow the script syntax
// quotations are interpretated as \\' in script code
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
// Gets the executing web page
Page tempPage = page;
// Checks if the handler is a Page and that the script isn't already on the page
if (tempPage != null & !tempPage.ClientScript.IsClientScriptBlockRegistered("alert"))
{
tempPage.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script); // this isn't working, but it works on a button click event.
}
}
}
Page Class
public partial class Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{ // i added a breakpoint here. It doesn't even pass through.
Alert.Show("hehehehe", this); //PopUp Shows up.
Timer1.Enabled = false; //Cancels Timer
Label1.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if update panel reloads
}
protected void Button1_Click1(object sender, EventArgs e)
{
Timer1.Enabled = true; //Starts Timer. It seems to refresh the page.
}
}
script
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test1.aspx.cs" Inherits="Test1" %>
<%# Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function delayer() {
setTimeout (function () {ShowPopUp()}, 15000);
}
delayer();
</script>
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
</div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" OnTick="Timer1_Tick" Interval="1000" Enabled="true">
</asp:Timer>
<asp:Label ID="Label1" runat="server" Text="PanelNotRefreshedYet"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="ShowPopUp();" />
</form>
</body>
</html>
I think you're confused. Timer1 is a server side control. So it will fire on the server side, if you're still processing the page, that is, and will have no effect on the client side. By the time it fires in your code, the page has likely already rendered so you'll see no effect from that Timer1 object's Timer1_Tick event. Since the page has completed rendering, you can't inject new JavaScript, modify the page, or anything like that. Remember that web development is a disconnected thing. You send a request, you get a response. There are no events by nature of the web. There are libraries out there for triggering events and such but I think that's way beyond what you're trying to achieve.
For client side "timer" you need to use JavaScript setTimeout method, which you have verified as working and is the proper way for you to achieve the delay you're looking to implement.
setTimeout (function () {ShowPopUp()}, 15000);
If you still want to do it in your Alert class, then get rid of Timer1 and have your Alert class inject the timeout in JavaScript:
protected void Button1_Click1(object sender, EventArgs e)
{
Alert.Show("He heee", this);
}
And in Alert, change your script to:
string script = "<script type=\"text/javascript\">setTimeout(function() {alert('" + cleanMessage + "');}, 15000);</script>";
Your button is doing a postback, so yes the page will be refreshed and your Page_Load function will run again. You should test for this using the IsPostback property.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostback) {
Timer1.Enabled = false;
Label2.Text = "Panel refreshed at: " +
DateTime.Now.ToLongTimeString(); // Checks if page reloads
}
}
You might want to look at showing the alert using JavaScript on the page rather than running it server side tho.
<script type="text/javascript">
function showPopup()
{
alert("Hey, click something already");
}
function delayer() {
setTimeout (showPopUp, 15000);
}
delayer();
</script>
Just put your message like this. Probably easier if your logic is simple.

Access the Label value on Page load in c# when value set through jQuery

I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)

Asp.Net Static method to refresh page

I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.
What I was wanting to do, is if a certain condition is met, to refresh the page completely.
Am I going to be able to do this in the current method that I have? here's my current stuff:
ASP.NET
<cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server"
ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1"
ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" />
Javascript
Sys.Application.add_load(function(){updateQueue();});
function updateQueue()
{
var queueShown = document.getElementById('<%= hiddenFieldQueueShown.ClientID %>').value;
if(queueShown == 1)
{
var behavior = $find('dp1');
if (behavior)
{
behavior.populate();
setTimeout('updateQueue()', 5000);
}
}
}
SERVER (C#)
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetQueueTable()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
try
{
// do stuff
}
catch (Exception ex)
{
// do stuff
}
return builder.ToString();
}
You can't do anything from your ASMX.
You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect.
You can force a Postback from Javascript, see this Default.aspx page for a example:
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function forcePostback()
{
<%=getPostBackJavascriptCode()%>;
}
</script>
</head>
<body onload="javascript:forcePostback()">
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Postbacking right now..."></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs
namespace ForcingApostback
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) Label1.Text = "Done postbacking!!!";
}
protected string getPostBackJavascriptCode()
{
return ClientScript.GetPostBackEventReference(this, null);
}
}
}
On the client-side, under any condition, you could then call the forcePostback() Javascript function to force the Postback.

Categories

Resources