Asp.Net Static method to refresh page - c#

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.

Related

Why I get error when I try to use variable of form class from designer?

In code behind I have property called ReportFeatures and Page_Load event:
public partial class FeatureList : System.Web.UI.Page
{
protected string ReportFeatures;
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
}
}
In designer I tried to access ReportFeatures variable:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%= ReportFeatures%>;
</script>
</head>
When page loaded I get this error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
Any idea why I get that error, and how to fix it?
Instead of using <%= ... %> block, try using data binding expression syntax (<%# ... %>), because <%= ... %> implicitly calls Response.Write() method in Page.Header which counts as code block while data binding expression doesn't count:
<head runat="server">
<title></title>
<script type="text/javascript">
window.reportFeatures = <%# ReportFeatures %>;
</script>
</head>
Then add Page.Header.DataBind() method in Page_Load event, because you want to bind ReportFeatures inside <head> tag which contains runat="server" attribute:
protected void Page_Load(object sender, EventArgs e)
{
IEnumerable<ReportFeature> featureProps = fim.getFeatureProperties();
ReportFeatures = featureProps.ToJson();
// add this line
Page.Header.DataBind();
}
More details about this issue can be found here.

C# how to retrieve Stripe Token from the Form.Submit

Can I ask how to retrieve the token from the coding/server side based on this script?
function stripeTokenHandler(token) {
// Insert the token ID into the form so it gets submitted to the server
var form = document.getElementById('payment-form');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripeToken');
hiddenInput.setAttribute('value', token.id);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
Thank you
Here is a basic example of submitting a webform with javascript and accessing the form collection on the server. I have hard-coded the stripe token value, I'm assuming you have that part covered.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication11.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<button onclick="stripeTokenHandler('some token value');">Submit Me</button>
</div>
</form>
</body>
<script>
function stripeTokenHandler(token) {
var form = document.getElementById('form1');
var hiddenInput = document.createElement('input');
hiddenInput.setAttribute('type', 'hidden');
hiddenInput.setAttribute('name', 'stripetoken');
hiddenInput.setAttribute('value', token);
form.appendChild(hiddenInput);
// Submit the form
form.submit();
}
</script>
</html>
Code Behind:
using System;
using System.Diagnostics;
namespace WebApplication11
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//any form inputs can be obtained with Request.Form[]
Debug.WriteLine(Request.Form["stripetoken"]);
}
}
}
}

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
}

confirm Box after the Data table gets data from sql

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.

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 :)

Categories

Resources