How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?
As far as I know I can call static method in server side from client side...
server side:
[WebMethod]
public static void method1()
{
}
client side:
<script language="JavaScript">
function keyUP()
{
PageMethods.method1();
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
It works. Now how do I call non-static method from client side?
You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.
1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)
2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx)
Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.
<%# WebService Language="C#" Class="SimpleService" %>
using System;
using System.Web.Services;
[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
[WebMethod]
public string GetMessage(string name)
{
return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
}
}
3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script language="javascript" type="text/javascript">
function callServer() {
SimpleService.GetMessage($get("Name").value, displayMessageCallback);
}
function displayMessageCallback(result) {
$get("message").innerHTML = result;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/SimpleService.asmx" />
</Services>
</asp:ScriptManager>
<div>
</div>
<h1>Hello World Example</h1>
<div>
Enter Name: <input id="Name" type="text" />
Call Server
<div id="message"></div>
</div>
</form>
</body>
</html>
I used the example I found from Scott Gu
Found Here.
No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(
$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax
on server side:
protected void Page_Load(object sender, EventArgs e)
{
if(!Request.QueryString.HasKeys() ||
string.IsNullOrEmpty(Request.QueryString["m"]))
{
//return error or something relevant to your code
}
var m = Request.QueryString["m"];
switch(m)
{
case "a":
a();
break;
.....
.....
}
}
Actually, you don't get to call non-static methods in this way.
When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.
C#
public string LoadString() {
return "my string";
}
JS/jQuery
$('#txt').val(<%= LoadString() %>);
as an answer to Pramulia
i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)
<%# Page Language="C#" AutoEventWireup="true" %>
<%# Implements Interface="System.Web.UI.ICallbackEventHandler" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head runat="server">
<title>Client Callbacks</title>
<script runat="server">
public void RaiseCallbackEvent(String eventArgument)
{
// Processes a callback event on the server using the event
// argument from the client.
}
public string GetCallbackResult()
{
// Returns the results of a callback event to the client.
string dateString = DateTime.Now.ToLongDateString();
return dateString;
}
void Page_Load(object sender, EventArgs e)
{
ClientScriptManager cm = Page.ClientScript;
String cbReference = cm.GetCallbackEventReference(this, "arg",
"ReceiveServerData", "");
String callbackScript = "function CallServer(arg, context) {" +
cbReference + "; }";
cm.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
</script>
<script type="text/javascript">
function ReceiveServerData(arg, context) {
Message.innerText = "Date from server: " + arg;
}
</script>
</head>
<body>
<h2>Client Callbacks Without Postbacks</h2>
<form id="form1" runat="server">
<input type="button" value="Callback"
onclick="CallServer('1', alert('Callback sent to Server'))" />
<br />
<span id="Message"></span>
</form>
</body>
</html>
If you want to call it using the same function, you can use the following code:
[WebMethod]
public static void method1()
{
ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
obj.yourFunctionName(ParametersIfAny);
}
I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.
Dave has written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).
C# Code:
[WebMethod]
public static string yourmethod(/*params*/)
{
return "Hello World!"
}
ASPX:
$.ajax({
type: 'POST',
data: /*Your Data*/,
dataType: 'JSON',
contentType: 'application/json',
url: '/yourpage.aspx/yourmethod',//Method to call
success: function(result, status) {
//handle return data
},
error: function(xhr, status, error) {
//handle error
}
});
Related
I'm writing a C# project,
One of my needs is to expose button when TextBox (not dynamic) have more then 1 letter, As long as i know changes (which includes functions activation) will happen only between postacks.
Is there any possibilty to check the Texbox letter content without using postback (Includes skip on page load function).
Thanks Ahead.
Is there any possibilty to check the Textbox letter content without
using postback (Includes skip on page load function).
Assuming you are using ASP.NET Web Form, you could call WebMethod via Ajax.
After posting back to server via Ajax,
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="TextBox1" />
<button type="button" onclick="postData();">Post Data</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
function postData() {
var data = { text: $('#<%= TextBox1.ClientID %>').val() };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postdata") %>',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (msg) {
$('#<%= TextBox1.ClientID %>').val(msg.d);
}
});
}
</script>
</form>
</body>
</html>
Code Behind
using System;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostData(string text)
{
return text + DateTime.Now;
}
}
}
I read some forums and found an easier way to call a C# Method from JavaScript but it's not working. I did it in my live app and it didn't work so I took a fresh project and used the code as below:
ASPX Mark-up
<%# 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>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="btnMe" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>
Javascript
<script type="text/javascript">
function jdfun() {
PageMethods.CSFun(onSucess, onError);
}
function onSucess(result) {
alert(result);
}
function onSucess(result) {
alert(result);
}
</script>
C#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string CSFun()
{
string result = "Hey Yeah";
return result;
}
}
No Error No Exception. The Debugger is not even going into the C# code.
Can anyone help me out.
Thanks.
Edit
I didn't really know about this, but I read a little and fixed your code.
Here is the code that works:
js:
<script type="text/javascript">
function jsfun() {
PageMethods.CSFun(onSuccess, onError);
}
function onSuccess(result) {
alert(result);
}
function onError(result) {
alert(result);
}
</script>
aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<asp:ScriptManager ID="sm" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div>
<asp:Button ID="Button1" runat="server" OnClientClick="jsfun()" />
</div>
</form>
</body>
</html>
Basic Example to do the same
aspx page
<form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
<fieldset id="ContactFieldset">
<label>
Your Name
<input type="text" id="NameTextBox" /></label>
<label>
Email Address
<input type="text" id="EmailTextBox" /></label>
<label>
Your Message
<textarea id="MessageTextBox"></textarea></label>
<button onclick="SendForm();">
Send</button>
</fieldset>
</form>
Page Method (.cs)
using System;
using System.Web.Services;
public partial class ContactUs : System.Web.UI.Page
{
[WebMethod]
public static void SendForm(string name, string email, string message)
{
if (string.IsNullOrEmpty(name))
{
throw new Exception("You must supply a name.");
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
if (string.IsNullOrEmpty(message))
{
throw new Exception("Please provide a message to send.");
}
// If we get this far we know that they entered enough data, so
// here is where you would send the email or whatever you wanted
// to do :)
}
}
javascript function
function SendForm() {
var name = $get("NameTextBox").value;
var email = $get("EmailTextBox").value;
var message = $get("MessageTextBox").value;
PageMethods.SendForm(name, email, message,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
// Dispaly "thank you."
$get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
// Alert user to the error.
alert(error.get_message());
}
I am trying to modify a simply chat application for learning purposes. The only change i made was to change a button to a serverside control. The problem i have is that the first time i broadcast a message, it works, and the Clients.addNotification(msg) is called. Yet the second time, although the javascript works, at its final step, the javascript undos all the changes and the Clients.addNotification(..) is never called :/ It only works for the first time! I have to rebuild my project to see it working again (a page refresh won't work)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addNotification(message);
}
}
My aspx page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Client1.aspx.cs" Inherits="WebApplication1.WorkingWithHubs.Client1" %>
<!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>
<script src="../Scripts/jquery-1.6.4.js" type="text/javascript"></script>
<script src="../Scripts/jquery.signalR.min.js" type="text/javascript"></script>
<script src="/signalr/hubs" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addNotification = function (message) {
$('#messages').append('<li>' + message + '</li>');
var labelValue = $('#total').val();
$('#total').val(parseInt(labelValue, 10) + 1);
};
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="updatePanel" runat="server">
<ContentTemplate>
<input type="text" id="msg" runat="server" />
<asp:Button ID="btn" runat="server" Text="BroadCast" OnClick="btn_click" ClientIDMode="static" />
<input type="text" id="total" value="0" />
<ul id="messages">
</ul>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
My code behind:
public partial class Client1 : System.Web.UI.Page
{
public List<String> list = new List<String>();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_click(object sender, EventArgs e)
{
list.Add(msg.Value);
}
}
Once this example work I will shift the code to another application I am working on so that notifications can be immediately pushed to all clients.
I am a very beginner and I would appreciate all your help! Thanks a lot guys!
EDIT:
when checking out the network tab (on my chrome), for the first click I get a 'send' (signalR) and Client1.aspx and all works fine, for the second click onwards, I only get Client1.aspx, and no send whatsoever :/
for a quick and dirty solution, just place the update panel ONLY around the button, and remove
$("#btn").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
and instead, insert the following in the beginning
$('#form1').delegate('#btn', 'click', function () {
chat.send($('#msg').val());
});
Thanks to my friends shifty and red_square :)
net/C# application I have a Link button:
<asp:LinkButton runat="server" ID="LinkButton1"/>
When the user clicks this button I want to execute this javascript function:
document.getElementById('LinkButtonPrevious').click();
And change a Session variable:
Session["ID"] = 2;
The problem is that the session variable can only be changed in the code behind.
How can I execute both when the link button is clicked?
Thanks in advance
Changing a value server side requires either a full post of the page or an ajax call.
So you could add a HiddenField and set its value to 2 client side, and then in your server side button handler use that value to set the session variable.
Or you could do an ajax call to a web service.
As far a performing client and server side operations on the same click event, you can do the following. Add a server side Click handler as usual, then register a client side event with ClientScriptManager.RegisterOnSubmitStatement. Here's the example from MSDN:
<%# Page Language="C#"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
String cstext = "document.write('Text from OnSubmit statement');";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ClientScriptManager Example</title>
</head>
<body>
<form id="Form1"
runat="server">
<input type="submit"
value="Submit" />
</form>
</body>
</html>
You May have to Use ClientCallBack ...
here is an example of it..
MSDN lINK FOR CLIENT CALLBACK
<script type="text/ecmascript">
function LookUpStock() {
var lb = document.getElementById("ListBox1"); // this two statements set your javascript
var product = lb.options[lb.selectedIndex].text;
CallServer(product, ""); //this method contains code where you set session variable
}
function ReceiveServerData(rValue) {
document.getElementById("ResultsSpan").innerHTML = rValue;
}
</script>
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.