Calling Javascript (Raphael.js library) from C# codebehind in ASP.NET - c#

I'm trying to call some function from my code behind in C#. I was searching how to do this and was able to call an alert to display when I wanted it to. However, I don't know how to call other things!
This is what I need to call from the code behind:
var paper = Raphael("paper1", 800, 800);
var Plan = paper.path("M100, 100 a 50, 50 0 0,1 50, 50 l -50 0 l 0, -50");
Plan.attr({ fill: "#FF6600" });
I've tried these on a plain HTML file but I'm not able to use it. I'm also using a master page and most of the examples I've found have been without master pages so I'm pretty lost on this.
Anyone can help?

Create a Javascript function in the .aspx page and then call the function from code behind like so:
Function in html Code
function dostuff()
{
// code here
}
C# code in code behind
protected void callmethod()
{
StringBuilder oSB = new StringBuilder();
Type cstype = this.GetType();
try
{
oSB.Append("<script language=javaScript>");
oSB.Append("dostuff();");
oSB.Append("</script>");
Page.ClientScript.RegisterClientScriptBlock(cstype, Guid.NewGuid().ToString(), oSB.ToString(), false);
}
catch (Exception ex)
{
throw ex;
}
finally
{
oSB = null;
}
}

Javascript can only be called on the client side. If you absolutely need to call it from your serverside, you can use a asp:HiddenField's value as a flag for when you need the javascript code executed upon returning, and then run the needed javascript if the requirements are met.
But its not a nice solution, you should probably try to separate the server and the client.
Hope this helps, in any case!

Related

c# change value of javascript variable from code behind

I have a variable named "tempVariable" in my jquery file.
now I need to change its value from code behind in c#.
What I have done till now is
in my C# code
public void changeValueInJquery()
{
bool newVal = false;
Page.ClientScript.RegisterClientScriptBlock(
GetType(),
"key", "ChangeValue(" + newVal + ");", true);
}
my jquery code is as
function ChangeValue(value1) {
alert(value1);
tempVariable = value1;
}
The issue is that ChangeValue() function never gets hit.
Am I going wrong somewhere?
may be '...' is required to pass value...
Try this :
Page.RegisterStartupScript("changevalue", "<script>ChangeValue('" + newVal + "');</script>");
I would check in a JS debugger to see if you are getting any errors.
But generally try using Page.ClientScript.RegisterStartupScript(); instead if you are calling functions already present in the page. This will ensure that the script block is rendered at the bottom of the page and not for example before the ChangeValue function.
As other people have mentioned, this is nothing to do with jQuery.

Running JavaScript in page from the backend (AJAX)?

I'm new to integrating JavaScript into a web site, but I'm going to need it often in my web site.
Here is an example:
Assuming I have the function:
showAlert()
Say I have:
<div id="some_div">
</div>
Could someone provide me some kind of example that would do this:
If I have a button and the user clicks it, this should raise an event in the backend and call some method in my C# file. Then my C# file should be able to call some other javascript method of the front end which would call showAlert() and display the alert in the div.
This is what I can't seem to find any information on.
The basic idea of passing information to and from the server. Any help with this would be really appreciated.
Thanks
Your best bet is to use a framework like jquery, then bind to the button, call the service, and handle the response. The below is a quick example of this.
$(document).ready(function()
$('#Button1').bind('click', function () {
// This grabs the page you are in so that you can call it correctly
var pagePath = window.location.pathname;
var testId = $("#some_div").val();
var url = pagePath + "/TestService";
$.post(url, { id: testId },
function (data) {
showAlert(data);
}
});
};
});
First, you need to make sure the document is ready at some point. Bind allows the the button to be bound when the document loads. Then, by clicking it, you execute the anonymous function that grabs the testId, calls your service, and handles the data response in a success callback.
Hope that gets you started in the right direction!
EDIT: Added backend webforms "service" exposure
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string TestService(string id)
{
var string = DBCollection.FirstOrDefault(x => x.id == id); // Or whatever you want to return the data
return "You called me on " + DateTime.Now.ToString() + "with " + string;
}
}
This would allow you to call the "WebMethod exposed on your page. For more help with this, please see the following link.
http://www.tugberkugurlu.com/archive/asp-net-web-forms---calling-web-service-page-methods-using-jquery
EDIT: Additional Considerations when performing this type of approach in webforms.
Calling a webmethod with jquery in asp.net webforms

Passing prompt box value from javascript function- PostBack to c#

I'll try to do the best I can to articulate what I'm trying to do.
Let me preface by saying that I am very new to C# and ASP.NET and have minimal experience with javascript.
I have a javascript function that invokes a prompt box. The overall picture is - if input is entered - it will be saved to a column in the database.
I'm drawing a blank on passing the value from the prompt box to the PostBack in c#.
function newName()
{
var nName = prompt("New Name", " ");
if (nName != null)
{
if (nName == " ")
{
alert("You have to specify the new name.");
return false;
}
else
{
// i think i need to getElementByID here???
//document.forms[0].submit();
}
}
}
This is what I have in C#:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//I have other code that works here
}
else
{
//I'm totally lost here
}
}
I'm trying to figure out how to make that call for the input from the javascript function.
I've spent the last few hours looking online and in books. Been overwhelmed.
EDIT
i did a little tweeking to fit what I'm trying to do....
<asp:HiddenField ID="txtAction" runat="server" Value="" />
document.forms(0).txtAction.Value = "saveevent";
document.forms(0).submit();
trying to figure out how to insert the string into the table now.....
string nEvent = Request.Form["event"];
if (txtAction.Value == "saveevent") {
nName.Insert(); //am i on the right track?
}
Well, here's one possible way (untested but should give you the basic idea). You could place a hidden field on your form to hold the value of the prompt:
<input type="hidden" id="hiddenNameField" runat="server" value="">
Then prompt the user for the value, set it to the hidden field, and then submit your form:
document.getElementById('hiddenNameField').value = nName;
document.forms(0).submit();
Then in your code-behind you can just access hiddenNameField.Value.
if you are trying to call the method on the back side using the java script you can try using the web method approach.
for instance you have a function that will call the SendForm method
function SendForm() {
var name = $("#label").text();
PageMethods.SendForm(name,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
}
function OnFailed(error) {
}
and you have the method that will be called from javascript.
[WebMethod(enableSession: true)]
public static void SendForm(string name)
{
}
<script language='Javascript'>
__doPostBack('__Page', '');
</script>
Copied from Postback using javascript
I think you need AJAX request here. I suggest usage of jQuery, since do the dogs work for you... Otherwise, you will have to implement a lot of already written general code for AJAX processing.
Something as the following one:
function PromptSomewhere(/* some args if needed*/)
{
var nName = prompt("New Name", " ");
// Do process your prompt here... as your code in JS above. Not placed here to be more readable.
// nName is used below in the AJAX request as a data field to be passed.
$.ajax({
type: "post", // may be get, put, delete also
url: 'place-the-url-to-the-page',
data {
name: nName
// You may put also other data
},
dataType: "json",
error: PromptFailed,
success: OnPromptComplete
});
}
function PromptFailed(xhr, txtStatus, thrownErr) // The arguments may be skipped, if you don't need them
{
// Request error handling and reporting here (404, 500, etc.), for example:
alert('Some error text...'); // or
alery(txtStatus); // etc.
}
function OnPromptComplete(res)
{
if(!res)
return;
if(res.code < 0)
{
// display some validation errors
return false;
}
// display success dialog, message, or whatever you want
$("div.status").html(result.message);
}
This will enable you to send dynamically data to the server with asynchronous request. Now C#:
using System.Web.Script.Serialization;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack && ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string nName = Request.Form["name"];
// do validation and storage of accepted value
// prepare your result object with values
result.code = some code for status on the other side
result.message = 'Some descriptive message to be shown on the page';
// return json result
JavaScriptSerializer serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(result));
}
}
Notes: If you use ASP.NET MVC 2 or higher I think, you will be able to use JsonResult actions and Request.IsAjaxRequest (I think was the name), and many other facilities and improvements of ASP.NET - ASP.NET MVC is the new approach for creating web applications based on MVC pattern (architecture) and will replace ASP.NET Pages eventually in some time.
This is a very good resource and contains the answer to your question:
How to use __doPostBack()
Basically, call PostbackWithParameter() function from your other JS function:
<script type="text/javascript">
function PostbackWithParameter(parameter)
{
__doPostBack(null, parameter)
}
</script>
And in your code-behind, grab the value for that parameter like so:
public void Page_Load(object sender, EventArgs e)
{
string parameter = Request["__EVENTARGUMENT"];
}

how to call the codebehind file methods in java script in asp.net2.0?

i can write methods like that
public void CompareEmail()
{
some code
}
public void UpdateEmail()
{
some code
}
public void InsertEmail()
{
some code
}
i am click the button onclientclick call the function like that
<asp:Button ID="btnSendNow" runat="server" CssClass="invdisp_btn" OnClick="btnSendNow_Click"
Text="Send Now" OnClientClick="return getEmailMessage()" />
java script function is like that
<script type="text/javascript" language="javascript">
function getEmailMessage()
{
var LoginID = document.getElementById('hdn').value;\\ i can pass 1 or 0
if (LoginID != 0)
{
//This place using CompareEmail() method How to write code comapare values not matching ask update confirm box
var ans;
ans = window.confirm('DO u want to update?');
if (ans == true)
{
// control.UpdateEmail();\\how to call UpdateMethod in .cs file
alert('updated');
}
else {
return false;
}
}
else {
var ans;
ans = window.confirm('DO u want to Insert values?');
if (ans == true)
{
PageMethods.InsertEmail();\\how to call InsertMethod in .cs file
// control.InsertEmail();
alert('Inserted');
}
else
{
return false;
}
}
}
</script>
how to write the code in java script function call the .cs file methods pls help me
Thank u
hemanth
You can achieve it by declaring your method as Web Methods in the code behind files.
Have look at this How to call a server-side method from client-side JavaScript !, it completely gives a solution to your problem.
Otherwise you can also use AJAx to do this.
You should try Pagemethods and ASP.net Ajax.
To call a server side method from client side, you have the following options:
Use ICallBackEventHandler
Use a Webservice with [ScriptService] attribute and call it's web methods from js
Use PageMethods. But that allows you to call static methods on your aspx page, only. Hence you won't be able to access any page controls.
I would recommend option 2, since it's the easiest.

javascript + asp.net - Calling javascript functions from c# and passing an object

I'm fairly new to web development.
Basically I'm using a HTML5 canvas to render content, and javascript functions which clear and render to the canvas.
I'm hoping to call a web service to get data that would affect content, which I believe is most easily done from C#, and was wondering how I could use this to periodically call a javascript function that would update values that are being rendered to the canvas?
To make this clearer, I have something like this:
Oh I'm also using jquery by the way, partly because I was told to.
Page.asp:
<body>
<form id="form1" runat="server">
<canvas id="canv" width="200" height="200">
Cannot display canvas because your web browser is a fail.
</canvas>
<script type="text/javascript">
var ctrls = new Array();
$(document).ready(function () {
var canvas;
var context;
canvas = $("#canv").get(0);
if (!canvas) {
alert("Failed to get canvas");
return;
}
context = canvas.getContext('2d');
if (!context) {
alert("Failed to get context");
}
var x;
x = new Object();
x.value = 0;
x.parent2d = context;
ctrls.push(x);
window.setInterval(Render, 25);
});
function Render() {
var i;
for (i = 0; i < ctrls.length; i++) {
ctrls[i].parent2d.clearRect(0, 0, 200, 200);
//Draw stuff.
}
}
function Update(newVal) {
var i;
for (i = 0; i < ctrls.length; i++) {
ctrls[i].value = newVal; //For example
}
}
</script>
</form>
</body>
What is the easiest (if it's even possible) way to call the Update(newVal) function from C# (Page.asp.cs), and how could this be set up to be done periodically?
What would be the limitations on what object(s) could be passed to this function?
Dictionary<String, Double>
would be very useful.
When exactly does update need to be called after page load? If it's every five seconds, it might be easier to carefully set up some sort of Javascript-based interval (making sure you are checking certain conditions to ensure that the interval quits upon any error conditions).
Depending on what data you have, you may want to setup a method in C# that given certain POST or GET parameters passed to it via a jQuery $.ajax() call.
For instance:
$(document).ready(function() {
var intervalId = setInterval("runUpdate()", 5000);
});
function runUpdate() {
//Make an ajax call here, setting up a variable called 'data'
update(data);//Data is newVal, which was setup in the ajax call above
}
That code would run the update function every five seconds.
Firstly from Javascript I would normally avoid using xml based web services. The returned data is XML which has lots of unessesary tags which can cause transfer to be slow.
Instead look at JSON. Its much faster. However not so easy for authentication. To help you understand its power both twitter and facebook use it in there APIs.
JQuery can consume JSON really easy
$.getJSON(someurl, function(jData) {
//use returned data
}
You might find it useful to read this:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Hope this helps.

Categories