Write on page load javascript function from code behind c# - 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>";

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>

Iframe doesn't show onload, but it does after manual reload

I'm using an Asp.net/C# environment and Visual Studio 2013 to create a web application.
I have a page (aspx) with only a single iframe in it, and a javascript method that uses jquery to put html into that frame.
<asp:Content runat="server" ID="MainSectionContent" ContentPlaceHolderID="MainSectionContentPlaceHolder">
<section runat="server" id="FrameSection" clientidmode="Static">
<asp:ContentPlaceHolder runat="server" ID="FrameSectionContentPlaceHolder" />
<iframe id="FrameContentFrame" name="FrameContentFrame" src="about:blank" seamless="seamless" onload=" loadFrameContent(); "></iframe>
</section>
<script type="text/javascript">
//<![CDATA[
function loadFrameContent() {
jQuery('#FrameContentFrame').contents().find('html').html('<%= FrameContent %>'); //FrameContent is a c# property which holds a syntactically correct html string
}
//]]>
</script>
</asp:Content>
In my code behind I fetch a long string from a server and store it in the property FrameContent. This long strings is syntactically correct html.
The result should be:
onload, the javascript method runs. The iframe is populated with html and thus the html string is shown to the user.
but what really happens:
nothing is shown. a Javascript error occurs saying "the function loadFrameContent is undefined". But its clearly there if I view the page source in my web browser. If I right click on the blank page where the frame should be, and choose "reload frame" (Google Chrome), the frame does show the Html.
So: the Html string is correct. the frame is correct. the frame can display the html correctly. However, the frame cannot display the Html onload, it needs an additional manual reload to actually show anything! I checked the page source on my browser and the Javascript function IS present, and the FrameContent property is populated with the correct html string.
As I see it, it looks like a timing issue. A blank iframe will be finished loading before your parent page, so it will call loadFrameContent before the parent page has finished parsing its dom (thus the method won't be registered). Get rid of the iframe onload and add this:
<script type="text/javascript">
//<![CDATA[
function loadFrameContent() {
jQuery('#FrameContentFrame').contents().find('html').html('<%= FrameContent %>'); //FrameContent is a c# property which holds a syntactically correct html string
}
$(loadFrameContent);
// Or if you're using an older version of jQuery
//$(document).ready(loadFrameContent);
//]]>
</script>

JavaScript functions prevent C# functions from being executed?

On my aspx page I have two buttons. One calls some javascript and the other calls a C# function on the code-page. When I call the javascript file in the head of the document, the JavaScript function works well but the C# does not. Clicking on the button does not do anything. If I remove the javascript call then the C# function works normally.
How can I overcome this? It seems as if it is expecting to find the C# function within the JavaScript file.
ASP:
<head>
<script src="MyFunctions.js" language="javascript" type="text/javascript"></script>
</head>
<body>
<asp:Button id="btn1" Text="Submit" runat="server" OnClick="buttonSumbit_Click" />
<asp:Button id="btn2" Text="Show" runat="server" OnClientClick="buttonShow_Click()" />
</body>
C#:
protected void buttonSumbit_Click(object sender, EventArgs e)
{
//SOME CODE HERE
}
JavaScript:
function buttonShow_Click()
{
//SOME CODE HERE
}
You need to put all Asp.Net server controls inside a <form runat="server"></form> tag
You need to modify your javascript function call to be like this
<asp:Button id="btn2" Text="Show" runat="server" OnClientClick="return buttonShow_Click()" />
and make sure that your javascript function returns true so postback (execute C# function) happens. If your javascript function return false, postback to server won't happen.
I Suggest you to use this for calling javascript functions:
OnClientClick="if(!hidepopup())return false;"
you can also call javascript functions from codebehind:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Call my function", "jsfunction();", true);

<script> tag get disappeared from rendered HTML after ajax postback action

I have a webpage with one <asp:updatePanel>. In the end of the webpage, some javascript method is added and called such as :-
The updatePanel code used is as follows:-
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
Some controls like repeater etc..
</ContentTemplate>
</asp:UpdatePanel>
<script type="text/javascript">
alert('hi');
MethodCall();
</script>
After some ajax postback action happened on the page, when i see the webpage html using the "View Source". The script tag code area gets disappeared from the webpage html. And this causes the problem at the place where js method is called.
I don't understand why this is happening? Why it is removing the JS code block after the ajax postback action.
Pls suggest some workaround or any solution to my problem.
Thx
You can also add the following js function, that is called by the ASP.Net AJAX client script library.
function pageLoad(sender, args)
{
if (args.get_isPartialLoad())
{
get_isPartialLoad is true when a partial postback has occurred.
}
}

Calling JavaScript Function From CodeBehind

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.

Categories