Calling JavaScript Function From CodeBehind - c#

Can someone provide good examples of calling a JavaScript function From CodeBehind and Vice-versa?

You may try this :
Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

Calling a JavaScript function from code behind
Step 1 Add your Javascript code
<script type="text/javascript" language="javascript">
function Func() {
alert("hello!")
}
</script>
Step 2 Add 1 Script Manager in your webForm and Add 1 button too
Step 3 Add this code in your button click event
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);

C# to JavaScript: you can register script block to run on page like following:
ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);
replace alert() part with your function name.
For calling C# method from JavaScript you can use ScriptManager or jQuery. I personally use jQuery. You need to decorate the method that you want to call from JavaScript with WebMethod attribute. For more information regarding calling C# method (called PageMethod) from jQuery you can refer to Dave Ward's post.

If you need to send a value as a parameter.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);

You can not do this directly. In standard WebForms JavaScript is interpreted by browser and C# by server. What you can do to call a method from server using JavaScript is.
Use WebMethod as attribute in target methods.
Add ScriptManager setting EnablePageMethods as true.
Add JavaScript code to call the methods through the object PageMethods.
Like this:
Step 1
public partial class Products : System.Web.UI.Page
{
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<Product> GetProducts(int cateogryID)
{
// Put your logic here to get the Product list
}
Step 2: Adding a ScriptManager on the Page
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
Step 3: Calling the method using JavaScript
function GetProductsByCategoryID(categoryID)
{
PageMethods.GetProducts(categoryID, OnGetProductsComplete);
}
Take a look at this link.
To call a JavaScript function from server you can use RegisterStartupScript:
ClientScript.RegisterStartupScript(GetType(),"id","callMyJSFunction()",true);

Another thing you could do is to create a session variable that gets set in the code behind and then check the state of that variable and then run your javascript. The good thing is this will allow you to run your script right where you want to instead of having to figure out if you want it to run in the DOM or globally.
Something like this:
Code behind:
Session["newuser"] = "false"
In javascript
var newuser = '<%=Session["newuser"]%>';
if (newuser == "yes")
startTutorial();

You cannot. Codebehind is running on the server while JavaScript is running on the client.
However, you can add <script type="text/javascript">someFunction();</script> to your output and thus cause the JS function to be called when the browser is parsing your markup.

You can use literal:
this.Controls.Add(new LiteralControl("<script type='text/javascript'>myFunction();</script>"));

Working Example :_
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage2.Master" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="NAMESPACE_Web.History1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function helloFromCodeBehind() {
alert("hello!")
}
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<div id="container" ></div>
</asp:Content>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace NAMESPACE_Web
{
public partial class History1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "helloFromCodeBehind()", true);
}
}
}
Possible pitfalls:-
Code and HTML might not be in same namespace
CodeBehind="History.aspx.cs" is pointing to wrong page
JS function is having some error

IIRC Code Behind is compiled serverside and javascript is interpreted client side. This means there is no direct link between the two.
What you can do on the other hand is have the client and server communicate through a nifty tool called AJAX. http://en.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML

ScriptManager.RegisterStartupScript(this, this.Page.GetType(),"updatePanel1Script", "javascript:ConfirmExecute()",true/>

I've been noticing a lot of the answers here are using ScriptManager.RegisterStartupScript and if you are going to do that, that isn't the right way to do it. The right way is to use ScriptManager.RegisterScriptBlock([my list of args here]). The reason being is you should only be using RegisterStartupScript when your page loads (hence the name RegisterStartupScript).
In VB.NET:
ScriptManager.RegisterClientScriptBlock(Page, GetType(String), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", True)
in C#:
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "myScriptName" + key, $"myFunctionName({someJavascriptObject})", true);
Of course, I hope it goes without saying that you need to replace key with your key identifier and should probably move all of this into a sub/function/method and pass in key and someJavascriptObject (if your javascript method requires that your arg is a javascript object).
MSDN docs:
https://msdn.microsoft.com/en-us/library/bb338357(v=vs.110).aspx

This is how I've done it.
HTML markup showing a label and button control is as follows.
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblJavaScript" runat="server" Text=""></asp:Label>
<asp:Button ID="btnShowDialogue" runat="server" Text="Show Dialogue" />
</div>
</form>
</body>
JavaScript function is here.
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
Code behind to trigger the JavaScript function is here.
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";

ScriptManager.RegisterStartupScript(Page, GetType(), "JavaFunction", "AlertError();", true);
using your function is enough

Try This in Code Behind and it will worked 100%
Write this line of code in you Code Behind file
string script = "window.onload = function() { YourJavaScriptFunctionName(); };";
ClientScript.RegisterStartupScript(this.GetType(), "YourJavaScriptFunctionName", script, true);
And this is the web form page
<script type="text/javascript">
function YourJavaScriptFunctionName() {
alert("Test!")
}
</script>

this works for me
object Json_Object=maintainerService.Convert_To_JSON(Jobitem);
ScriptManager.RegisterClientScriptBlock(this,GetType(), "Javascript", "SelectedJobsMaintainer("+Json_Object+"); ",true);

Since I couldn't find a solution that was code behind, which includes trying the ClientScript and ScriptManager like mutanic and Orlando Herrera said in this question (they both somehow failed), I'll offer a front-end solution that utilizes button clicks to others if they're in the same position as me. This worked for me:
HTML Markup:
<asp:button ID="myButton" runat="server" Text="Submit" OnClientClick="return myFunction();"></asp:button>
JavaScript:
function myFunction() {
// Your JavaScript code
return false;
}
I am simply using an ASP.NET button which utilizes the OnClientClick property, which fires client-side scripting functions, that being JavaScript. The key things to note here are the uses of the return keyword in the function call and in the function itself. I've read docs that don't use return but still get the button click to work - somehow it didn't work for me. The return false; statement in the function specifies a postback should NOT happen. You could also use that statement in the OnClientClick property: OnClientClick="myFunction() return false;"

I used ScriptManager in Code Behind and it worked fine.
ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "CallMyFunction", "confirm()", true);
If you are using UpdatePanel in ASP Frontend.
Then, enter UpdatePanel name and 'function name' defined with script tags.

Thank "Liko", just add a comment to his answer.
string jsFunc = "myFunc(" + MyBackValue + ")";
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "myJsFn", jsFunc, true);
Added single quotes (') to variable, otherwise it will give error message:
string jsFunc = "myFunc('" + MyBackValue + "')";

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

You can expose C# methods on codebehind pages to be callable via JavaScript by using the ScriptMethod attribute.
You cannot call JavaScript from a CodeBehind - that code exists solely on the client.

Related

How to call js file function from code behind page

I have following function in .js file and i need to call it from code behind page after saving a record.
I have registered scipt file in aspx page
aspx file
<script type="text/javascript" src="/scripts/visit-flash-report.js"></script>
.js file
function reloadDocTab() {
alert('hello');
$('#frmDocs').attr('src', $('#frmDocs').attr('src'));
}
Code behind page
I have tried the function but it is not working
Page.ClientScript.RegisterOnSubmitStatement(Me.[GetType](), "reload function", "return reloadDocTab();")
If I understand what your trying to do. You want to save the record on postback then when the page reloads call the javascript function.
Try this:
PageBody.Attributes.Add("onload", "reloadDocTab()");
Try this:
.aspx
<script type="text/javascript" src="/scripts/visit-flash-report.js"></script>
<asp:Literal runat="server" ID="litJS" />
.cs
litJS.Text = #"<script type='text/javascript'>alert('hello');</script>";
If you dont need to execute the script on a different postback you might want to assign an empty string to the literal.
Try one of these:
Page.ClientScript.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
OR
ClientScript.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
OR
ScriptManager.RegisterStartupScript(this.GetType(), "ScriptKey", "reloadDocTab()", true);
And i think you might need to refrence the .JS file in the head tag
<head runat="server">
<script src="~/scripts/visit-flash-report.js"></script>
</head>

Write on page load javascript function from code behind c#

i have this function on my aspx page:
<script type="text/javascript">
function pageLoad() {
//code here
}
</script>
and i need to override this function dymanically from my .cs
i have tried to use Page.ClientScript.RegisterClientScriptBlock and Page.ClientScript.RegisterStartupScript but that only creates a new javascript function.
Any ideas?
Try creating an empty div on your ASPX page with runat="server", and then setting the InnerHtml to the JavaScript code. This offers a lot of flexibility and will allow you to apply whatever logic you need depending on your situation.
.aspx
<div id="script" runat="server">
</div>
.cs
script.InnerHtml = "<script type='text/javascript'>//your javascript here</script>";

asp.net passing values from JS/jquery to code behind c#

I have tried "every" possible way of sending the screen.width vlaue from the JS script on the aspx page to the c# in the code behind and while I can see the screen.width being assigned correctly it never gets assigned to my hidden field value.
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:HiddenField ID="hiddenfield" runat="server" />
<script type="text/javascript" language="javascript">
$(function(){
$('#hiddenfield').val(screen.width);
});
</script>
other content
</asp:Content>
and the code behind:
protected void btnChartGo_Click(object sender, EventArgs e)
{
string s = hiddenfield.Value;
}
No matter what I try s is always ""
Something wrong with the above, everyone seems to be doing it like that and it works?
The ID of the rendered hidden field isn't "hiddenfield" - it'll be something like ctl00_bodycontent_hiddenfield.
Try using
$('[id$="hiddenfield"]')
as the selector instead.
<asp:HiddenField ID="hiddenfield" runat="server" ClientIDMode="Static">
</asp:HiddenField >
Make sure client ID mode of your hidden field is static if you are using ASP.NET 4 or use
$('#<%= hiddenfield.ClientID %>').val(screen.width);
This should get the right selector:
$('#<%= hiddenfield.ClientID %>').val(screen.width);
Check the view source of the page and find out proper id of the element and then use jquery selector over it and then at the page load check for request.form collection to check if hidden variable is coming in post request or not

Angle Brackets in Page head element

Iam new to ASP.NET with prev. PHP experience (which meaby is causing this problem) and Iam having small problem passing data from codebehind to view-source.
I declared string variable on codebehind side such as:
...
public string mystring = "Scotty";
protected void Page_Load(object sender, EventArgs e)
{
...
So now I want to use it in view-code but when I put it in angle brackets (<%: or <%=) and put it in head element I got no access to this value. On the other hand when I put it in BODY element everything is ok.
My failing example (simplified):
<head runat="server">
<script language="javascript">
function beamMeUp()
{
alert(<%=mystring;%>);
}
</script>
</head>
<body>
<input type="button" onclick="javascript:beamMeUp" value="Warp6" />
</body>
Can anyone explain it to me why I can't use it (the <%=mystring;%>) in HEAD but i can use it in BODY ?
Best regards
The semicolon isn't necessary when using <%=. Think of it as writing:
<% Response.Write(mystring); %>
You will want to wrap that in quotes as well.
alert("<%=mystring %>");
Without quotes would be: alert(Scotty);
which does not make much sense unless you have a javascript variable called Scotty.
It should give you an alert box showing undefined
The code-behind variable mystring is available in the <head>. C# IntelliSense isn't displaying for it since it's inside of a <script> tag.
Your problem may be that you have
<head runat="server">...
I believe this causes ASP .NET to construct an HtmlHead object which you can reference from Page.Head. However, you cannot have inline constructs such as <% .. %> and <%= %> when doing this. I believe this is also true of other ASP .NET controls such as
<asp:TreeView ...>
<asp:TreeViewItem> <%= will cause error! %> </asp:TreeViewItem
</asp:TreeView>
http://geekswithblogs.net/mnf/archive/2007/11/14/code-render-blocks-not-always-work-inside-server-controls.aspx
You really had three problems:
1.) You have a javascript error as pointed out by the first responder when he told you to use:
alert("<%=mystring %>");
2.) You have an ASP .NET error because you can't use <%= %> inside a tag that has runat="server".
3.) Another javascript error in your onclick assignment. Note it is better to wire up events in code using attachEvent and addEventListener. Your onclick assignment does not need the javascript: in front. You might do this for an href attribute, but not an onclick. In the onclick, you are already executing javascript. You could have onclick="alert('yo!')" which would work. Also, when executing a function, you must include the parenthesis, so you should have onclick="beamMeUp();" (semi colon optional).
Your revised code should look more like:
<head> <!-- notice runat="server" has been removed -->
<script type="text/javascript">
function beamMeUp()
{
alert("<%=mystring;%>");
}
</script>
</head>
<body>
<input type="button" onclick="beamMeUp();" value="Warp6" />
</body>
Note: I tried the code above and it works. I made these changes
removed runat="server" from the <head> tag
added double quotes to alert("<%=mystring;%>");
changed onclick event to onclick="beamMeUp();" NOT onclick="javascript:beamMeUp".
Good luck.

Javascript function call to ASP.NET

My Javascript function calling a sever side callback function.
This is working fine when I give alert(). If I comment alert() then the browser throw a warning ..
My function is
function callMe(){
var input = 'input parameter list';
var val= <%=gridCtrlUsers.ClientID%>.callbackControl.Callback(input);
// If I comment this alert ,it would throw a browser warning.
alert(val) // This prints true or false
}
Could anyone please help me ?
I agree with José this doesnt look standard.
If its a custom control that has a client side API then have you tried just typing out its identifier rather than using the <% %> tags...
You havnt mentioned what 3rd party toolkit your using but I know with DevExpress their components (such as the grid) have a property that allows you to set the client side instance name. You can get the grid to then call back from your client code by doing something like gridClientName.PerformCallback().
If it is ComponentArt's grid you are using then I think you can set the grids client name with the ClientObjectId property and then use gridClientName.callback() in your Javascript.
If you just want to call an ASP.NET function from your Javascript code you could use an ASP.NET Script Manager AJAX control. I will give you an example below...
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<script runat="server">
[System.Web.Services.WebMethod]
public static String Msg()
{
String userName = "Chalkey";
return userName;
}
</script>
<script type="text/javascript">
PageMethods.Msg(OnSucceed);
function OnSucceed(result)
{
alert(result);
}
</script>
Hope some of this is useful! :)

Categories