Invoke JavaScript from C# code behind [duplicate] - c#

This question already has answers here:
Calling JavaScript Function From CodeBehind
(21 answers)
Closed 9 years ago.
I am trying to learn asp.net. Assuming that I have this code:
if (command.ExecuteNonQuery() == 0)
{
// JavaScript like alert("true");
}
else
{
// JavaScript like alert("false");
}
How to I can invoke JavaScript from C# code behind? How to do that by putting that JavaScript in Scripts directory which is created by default in MS Visual Studio?

Here is method I will use from time to time to send a pop message from the code behind. I try to avoid having to do this - but sometimes I need to.
private void LoadClientScriptMessage(string message)
{
StringBuilder script = new StringBuilder();
script.Append(#"<script language='javascript'>");
script.Append(#"alert('" + message + "');");
script.Append(#"</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "messageScript", script.ToString());
}

You can use RegisterStartupScript to load a javascript function from CodeBehind.
Please note that javascript will only run at client side when the page is render at client's browser.
Regular Page
Page.ClientScript.RegisterStartupScript(this.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);
Ajax Page
You need to use ScriptManager if you use ajax.
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myfunc" + UniqueID,
"myJavascriptFunction();", true);

Usually these "startupscripts" are handy for translations or passing settings to javascript.
Although the solution Mike provided is correct on the .Net side I doubt in a clean (read: no spaghetti code) production environment this is a good practice. It would be better to add .Net variables to a javascript object like so:
// GA example
public static string GetAnalyticsSettingsScript()
{
var settings = new StringBuilder();
var logged = ProjectContext.CurrentUser != null ? "Logged" : "Not Logged";
var account = Configuration.Configuration.GoogleAnalyticsAccount;
// check the required objects since it might not yet exist
settings.AppendLine("Project = window.Project || {};");
settings.AppendLine("Project.analytics = Project.analytics || {};");
settings.AppendLine("Project.analytics.settings = Project.analytics.settings || {};");
settings.AppendFormat("Project.analytics.settings.account = '{0}';", account);
settings.AppendLine();
settings.AppendFormat("Project.analytics.settings.logged = '{0}';", logged);
settings.AppendLine();
return settings.ToString();
}
And then use the common Page.ClientScript.RegisterStartupScript to add it to the HTML.
private void RegisterAnalyticsSettingsScript()
{
string script = GoogleAnalyticsConfiguration.GetAnalyticsSettingsScript();
if (!string.IsNullOrEmpty(script))
{
Page.ClientScript.RegisterStartupScript(GetType(), "AnalyticsSettings", script, true);
}
}
On the JavaScript side it might look like this:
// IIFE
(function($){
// 1. CONFIGURATION
var cfg = {
trackingSetup: {
account: "UA-xxx-1",
allowLinker: true,
domainName: "auto",
siteSpeedSampleRate: 100,
pluginUrl: "//www.google-analytics.com/plugins/ga/inpage_linkid.js"
},
customVariablesSetup: {
usertype: {
slot: 1,
property: "User_type",
value: "Not Logged",
scope: 1
}
}
};
// 2. DOM PROJECT OBJECT
window.Project = window.Project || {};
window.Project.analytics = {
init: function(){
// loading ga.js here with ajax
},
activate: function(){
var proj = this,
account = proj.settings.account || cfg.trackingSetup.account,
logged = proj.settings.logged || cfg.customVariablesSetup.usertype.value;
// override the cfg with settings from .net
cfg.trackingSetup.account = account;
cfg.customVariablesSetup.usertype.value = logged;
// binding events, and more ...
}
};
// 3. INITIALIZE ON LOAD
Project.analytics.init();
// 4. ACTIVATE ONCE THE DOM IS READY
$(function () {
Project.analytics.activate();
});
}(jQuery));
The advantage with this setup is you can load an asynchronous object and override the settings of this object by .Net. Using a configuration object you directly inject javascript into the object and override it when found.
This approach allows me to easily get translation strings, settings, and so on ...
It requires a little bit knowledge of both.
Please note the real power of tis approach lies in the "direct initialization" and "delayed activation". This is necessary as you might not know when (during loading of the page) these object are live. The delay helps overriding the proper objects.

This might be a long shot, but sometimes I need a c# property/value from the server side displaying or manipulated on the client side.
c# code behind page
public string Name {get; set;}
JavaScript on Aspx page
var name = '<%=Name%>';
Populating to client side is generally easier, depending on your issue. Just a thought!

Related

C# parsing web site with ajax loaded content

If I recive a web site with this function I get the whole page, but without the ajax loaded values.
htmlDoc.LoadHtml(new WebClient().DownloadString(url));
Is it possible to load the web site like in gChrome with all values?
You can use a WebBrowser control to get and render the page. Unfortunately, the control uses Internet Explorer and you have to change a registry value in order to force it to use the latest version and even then the implementation is very brittle.
Another option is to take a standalone browser engine like WebKit and make it work in .NET. I found a page explaining how to do this, but it's pretty dated: http://webkitdotnet.sourceforge.net/basics.php
I worked on a little demo app to get the content and this is what I came up with:
class Program
{
static void Main(string[] args)
{
GetRenderedWebPage("https://siderite.dev", TimeSpan.FromSeconds(5), output =>
{
Console.Write(output);
File.WriteAllText("output.txt", output);
});
Console.ReadKey();
}
private static void GetRenderedWebPage(string url, TimeSpan waitAfterPageLoad, Action<string> callBack)
{
const string cEndLine= "All output received";
var sb = new StringBuilder();
var p = new PhantomJS();
p.OutputReceived += (sender, e) =>
{
if (e.Data==cEndLine)
{
callBack(sb.ToString());
} else
{
sb.AppendLine(e.Data);
}
};
p.RunScript(#"
var page = require('webpage').create();
page.viewportSize = { width: 1920, height: 1080 };
page.onLoadFinished = function(status) {
if (status=='success') {
setTimeout(function() {
console.log(page.content);
console.log('" + cEndLine + #"');
phantom.exit();
}," + waitAfterPageLoad.TotalMilliseconds + #");
}
};
var url = '" + url + #"';
page.open(url);", new string[0]);
}
}
This uses the PhantomJS "headless" browser by way of the wrapper NReco.PhantomJS which you can get through "reference NuGet package" directly from Visual Studio. I am sure it can be done better, but this is what I did today. You might want to take a look at the PhantomJS callbacks so you can properly debug what is going on. My example will wait forever if the URL doesn't work, for example. Here is a useful link: https://newspaint.wordpress.com/2013/04/25/getting-to-the-bottom-of-why-a-phantomjs-page-load-fails/
No its not possible in your example. Since it will load content as a string. You should render that string in "browser engine" or find any components which would do that for you.
I would suggest you to look into abotx they just announce this feature so maybe would be interesting for you but its not free.

how to passing value codebehind C# to javascript

Any one can help me..I want to pass the C# value to javascript..I only get pass 2 values only to the javascript..I dont know how to pass a tbSTime,tbETime and tbIndo2..Please help me..Thank You
This is code behind:
{
// get the meeting info based on the id
int id = Convert.ToInt32(Request["id"]);
MeetingClass.MeetingInfo m = MeetingClass.MeetingInfo.GetInfo(id);
// fill data
tbtitle2.Value = m.Title;
tbdate2.Value = m.Date.ToShortDateString();
tbSTime.Value = m.StartTime.ToShortTimeString();
tbETime.Value = m.EndTime.ToShortTimeString();
tbIndo2.Value = m.Desc;
}
And this is javascript:
function getInfo() {
$('#<%=tbtitle.ClientID%>').val($('#<%=tbtitle2.ClientID%>').val());
$('#<%=tbdate.ClientID%>').val($('#<%=tbdate2.ClientID%>').val());
}
From what I can tell on your code, you are setting an asp:HiddenField (since you are using .Value) and then using that to populate your asp:TextBox w/ jQuery. If that is the case, then you need to do something like this.
$('#<%=aspTextBoxName1.ClientID%>').val($('#<%=tbSTime.ClientID%>').val());
$('#<%=aspTextBoxName2.ClientID%>').val($('#<%=tbETime.ClientID%>').val());
$('#<%=aspTextBoxName3.ClientID%>').val($('#<%=tbIndo2.ClientID%>').val());
Where aspTextBoxName1, aspTextBoxName2, aspTextBoxName3 are the names of your new textboxes.
I don't know if you really need those hidden form fields, there are easier ways to do this if you don't.
in controller:
ViewBag.tbSTime = tbSTime;
in view:
$('#<%=tbtitle.ClientID%>').val("<%= ViewBag.tbSTime %>");
Iam sorry but iam not sure what exactly you need, but from what i understood i can provide you with this:
If You want to send some value from Server side variables to Javascript function one way you can do this as follows,
function abc(x,y)
{
//Do you things here
}
and from server side call javascript code as follows
string a=textbox1.text;
string b=textbox2.text;
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "abc("+a+","+b+");", true);

javascript variable existence on page

I'm creating javascript Variable using c#.net inside code behind page and putting that variable on page using Page.ClientScript.RegisterClientScriptBlock(). So that variable is available on page and I can read(get) that variable value on client side using jquery.
I'm doing following:
C# :
category_columnNames += "var vertical_" + catItem.VerticalID + "_columnNames=['Tools','PersonID','Topic','Category','Cost','Company']";
Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "LoadColumnNames", category_columnNames, true);
By doing this let's say :var vertical_1_columnNames=['Tools','PersonID','Topic','Category','Cost','Company']; is on page. Now I want to first check if that variable(vertical_1_columnNames) exists on page or not. If yes then I need to get value of it (['Tools','PersonID','Topic','Category','Cost','Company']) on client side.I'm doing following on client side:
Client Side :
function ViewCartDirectLeadsGridInit(gridID) {
alert(gridID);//vertical_1_CategoryGrid
var vertical = gridID.toString().split('_')[1];
var columnNames = "vertical_" + vertical + "_columnNames";
alert(columnNames); // vertical_1_columnNames
alert(typeof(columnNames));// string
alert(eval(columnNames)); // ['Tools','PersonID','Topic','Category','Cost','Company']
if (!window.columnNames) // This is not working.I want to check for existence of var vertical_1_columnNames
{
alert("success");
return false;
}
else{
// do something;
}
}
Any suggestion?
Thanks,
A
window.columnNames will search for a variable named "columnNames" not "vertical_" + vertical + "_columnNames". Use window[columnNames].

Javascript works on IE but not on Firefox and gives me error as Error: cprofiledetailscollapse is not defined

I use C#.net.
I wrote JavaScript for hide and show expand and collapse div accordingly. It work well in IE but not on Firefox, not even call the JavaScript function and gives me error as Error: ctl00_cpContents_dlSearchList_ctl08_profiledetailscollapse is not defined.
My JavaScript is as follows
function displayDiv(divCompact, divExpand) {
//alert('1');
var str = "ctl00_cpContents_";
var divstyle = new String();
// alert("ibtnShowHide" + ibtnShowHide);
divstyle = divCompact.style.display;
if (divstyle.toLowerCase() == "block" || divstyle == "") {
divCompact.style.display = "none";
divExpand.style.display = "block";
// ibtnShowHide.ImageUrl = "images/expand_img.GIF";
}
else {
// ibtnShowHide.ImageUrl = "images/restore_img.GIF";
divCompact.style.display = "block";
divExpand.style.display = "none";
}
return false;
}
ctl00_cpContents_dlSearchList_ctl08_profiledetailscollapse is an element id generated by ASP.NET. It's a profiledetailscollapse control inside dlSearchList.
JavaScript variable "ctl00_cpContents_dlSearchList_ctl08_profiledetailscollapse" is not
defined. Firefox does not automatically create, for each element with an id, a
variable in the global scope named after that id and containing a reference
to the element.
You might want to consider using jQuery to make sure that your DOM manipulation is cross-browser compatible.

How to read session values using jQuery

I am using c# and jQuery.
I have below code where I am setting the Session Variable using C# code.
if (!string.IsNullOrEmpty(results))
{
string[] array = results.Split(',');
string firstName = array[0];
string lastName = array[1];
string activeCardNo = array[2];
string memberShipTier = array[3];
string accessToken = array[4];
Session["skyFirstName"] = firstName.ToString();
Session["skyLastName"] = lastName.ToString();
Session["skyActiveCardNo"] = activeCardNo.ToString();
Session["skyMemberShipTier"] = memberShipTier.ToString();
Session["boolSignOn"] = "true";
Response.Redirect(fromPage);
Response.End();
}
Now I want to read these values (Session["skyFirstName"]) using jQuery so that I can set in my elements. Please suggest.
Session values are stored on the server and it is impossible to read them with client side javascript. One way to achieve this would be to expose some server side script or generic handler which would return the corresponding session value given a key and then use jQuery to send an AJAX request to this handler and read the value. You should be aware that by doing this the user can read all his session values. Be warned that exposing the same script for writing session values could be catastrophic from security standpoint.
Here's an example:
public class ReadSession : IHttpHandler, IReadOnlySessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write(new JavaScriptSerializer().Serialize(new
{
Key = context.Request["key"],
Value = context.Session[context.Request["key"]]
}));
}
public bool IsReusable
{
get { return true; }
}
}
and then query it:
$.getJSON('/ReadSession.ashx', { key: 'skyFirstName' }, function(result) {
alert(result.Value);
});
jquery runs on the client, which cannot directly access your server-side-session values. one solution is to provide a webservice which returns these values and use the webservice, another one would be to include the values in the page-response as JSON (e.g.) and access them on the client.
You cannot access the session variables with javascript as the session variables are server side rather than client side.
One work around that has already been mentioned is to use ajax to allow the javascript to communicate with the server side. This is fine, but possibly overly complicated for what you need.
Another, simpler solution would be to output the session variables into hidden input fields or as javascript variables in script tags which you can then access with the javascript.
jQuery is javascript, so in order to have those variables available you need to print out html code (at least one script tag) where you set the read-out session variables from C# as javascript variable.
An alternative would be to use an ajax request to get the session variables from a server script.

Categories