How to write this Javascript coding in C# code behind? - c#

<%--Confirmation Box--%>
<script type="text/javascript" language="javascript">
function alertbox() {
if (confirm("Are you sure?") == true)
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "YES";
}
else
{
document.getElementById('<%= hdnYesNo.ClientID %>').value = "NO";
}
}
</script>
How to rewrite this code in C# as codebehind? I would like have a confirm box with yes or no buttons.

protected void Page_Load(object sender, System.EventArgs e)
{
string csName = "PopupScript";
Type csType = this.GetType();
ClientScriptManager csm = Page.ClientScript;
if (!csm.IsStartupScriptRegistered(csType, csName)) {
StringBuilder sb = new StringBuilder();
sb.Append("<script>");
sb.Append("function alertbox() {");
sb.Append("if (confirm('Are you sure?') == true) ");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'YES';");
sb.Append("}");
sb.Append("else");
sb.Append("{");
sb.Append("document.getElementById('" + hdnYesNo.ClientID + "').value = 'NO';");
sb.Append("}");
sb.Append("</script>");
csm.RegisterStartupScript(csType, csName, sb.ToString());
}
}

you can use like this way
Page.ClientScript.RegisterStartupScript(this.GetType(), "Confi", "if(confirm('Are you sure?') == true){ document.getElementById('txtValue').value ='YES';}else{document.getElementById('txtValue').value ='NO';}", true);

You can use ClientScriptManager class and its methods, for example RegisterClientScriptBlock. Depends on when you want the javascript to execute.
See details here:
http://msdn.microsoft.com/en-us/library/System.Web.UI.ClientScriptManager_methods.aspx

You need javascript for this, it's not possible in code behind. Code behind is run on the server before the page is sent to the user, javascript is run on the user's computer.
If you want to get access to their answer in code behind (possible and straightforward), you can use ajax or you can postback.
If you want to have this popup to come up when you press on a .Net asp:button control, then you can put a javascript function in the "OnClientClick" attribute of the control.
EDIT: If you need help with any of the above, let us know and help will be provided :).
EDIT2: Due to the discussion below, I guess I should clarify: You can (obviously) construct javascript on the server side before passing it to the client, but the example you gave is NOT a case where you should be doing that (an example of where this might be a good idea would be a script that has variables read from a database or something similar that doesn't need to be dynamic between page loads).

another option is to create the script in the /View folder and user razor for generating the script.
then you could point to the page in the tag like
<script src="~/ScriptGenerator/MyScript" />
for pointing the controller ScriptGeneratorController that expose the action MyScript

Related

Invoke JavaScript from C# code behind [duplicate]

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!

Rapid, successfull new windows in ASP.NET/C# Loop via JavaScript

I'm attempting to open 1-6 potential valid popups (in reality it's a foreach item in a valid collection) via a registered startup script like this:
While (int i < 6)
{
ScriptManager.RegisterStartupScript(this.Page, typeof(System.Web.UI.Page), "OpenWin", "<script type='text/javascript'>openNewWin ('" + url + "')</script>", false);
i++;
}
The markup is as follows:
<head>
<script language="javascript" type="text/javascript">
function openNewWin(url)
{
var x = window.open(url, 'mynewwin', 'width=620,height=250,toolbar=1');
x.focus();
}
</script>
</head>
But I'm only seeing one window open, when i step through, the code seems to execute successfully, what gives?
In your window.open call, you are using the same name (mynewwin). Thus each subsequent call to open results in the URL being loaded into the first window with that name. You could use _blank and it would open each in a new window:
var x = window.open(url, '_blank', 'width=620,height=250,toolbar=1');
That being said, I agree that it's difficult to imagine this not being a poor user experience.

Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#

This isn't working:
Response.Write(" DELETE ");
<script language="javascript" type="text/javascript">
function Delete(path) {
path1 = unescape(path);
var myObject = new ActiveXObject("Scripting.FileSystemObject");
var myFolder = myObject.GetFolder(path1);
myFolder.Delete();
alert("Welcome");
}
</script>
But this worked.
Response.Write(" DELETE ");
<script language="javascript" type="text/javascript">
function Delete() {
alert("Welcome");
}
</script>
I tried with onclick for Delete() to get just ALERT it worked well.
But it isn't working when add the parameters.Can you help me please.Trying for this from long time please.
First of all, \u is escpae code for a hex digit. So better re-format it.
Second, href=view.aspx?type=notes is not a valid html syntax too. Double quotes please.
Third, please put some code to check if your javascript variables (myObject,myFolder) are valid (not null) before invoke any method against them.

ScriptManager.RegisterClientScriptBlock problem in updatepanel

Error: missing } in XML expression
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=FRXTn%2fX1N8Wy8C%2fdJqQmDjrOEECv%2fRwauMVX6ZTipAM%3d
line: 0, column: 188
code:
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
CODE:
public static void ShowAsync(string sMessage, MessageBoxTypes sType, Control control, Page pPage)
{
StringBuilder sb = new StringBuilder();
sb.Append("<script language='javascript'>");
string sMsg = sMessage;
sMsg = sMsg.Replace("\n", "\\n");
sMsg = sMsg.Replace("\"", "'");
sb.Append(#"$(document).ready(function() {");
sb.Append(#"Sexy." + sType + #"( """ + sMsg + #""" );");
sb.Append(#"});");
sb.Append(#"</" + "script>");
ScriptManager.RegisterClientScriptBlock(pPage, typeof(Page), control.ClientID, sb.ToString(), true);
}
if i change true to false in RegisterClientScriptBlock then i get
error: $ is not defined
source code: http://localhost:3811/Clinic/ScheduleModule/ManageWorkingTime.aspx?ScheduleId=dH0ry1kng6MwGCRgCxXg8N5nCncbzPzn3TAOEI0tAY4%3d
line: 0
i call this popup like:
MessageBox.ShowAsync("Can not copy files.", MessageBoxTypes.alert, this, Page);
What can be wrong. If i copy this (JQUERY)
<script language='javascript'>$(document).ready(function() {Sexy.alert( "Can not copy files." );});</script>
into some .aspx page popup works. But if i call it from code behind and daypilot pro in this updatepanel form then i get this error.
Can be problem that two ajax framewroks mixed themself? How to prevent this?
i try with jquery.noConflict but it is the same
$.noConflict();
jQuery(document).ready(function() { Sexy.alert("Can not copy files."); });
Thx
If you change the last parameter in RegisterClientScriptBlock from true to false it will not add the script tag anymore. Currently with the setting to true, you have the script tag twice. Not sure what happens, but can't be good :-)
$ sounds like jquery? You don't mention what you are using? I mix ASP.NET Ajax with jquery and that works fine. What Version are you on?

Implementing javascript in c# code behind

Morning all.
I have the following javascript in my code in front
<script type="text/javascript" src="~/VDSReporting/jquery.js"></script> <script type="text/javascript">
function ShowImage() {
document.getElementById('tbxProdAC')
.style.backgroundImage = 'url(/images/vds/progress.gif)';
document.getElementById('tbxProdAC')
.style.backgroundRepeat = 'no-repeat';
document.getElementById('tbxProdAC')
.style.backgroundPosition = 'right';
}
function HideImage() {
document.getElementById('tbxProdAC')
.style.backgroundImage = 'none';
}
</script>
How do I go about 'converting' this and only having it present in c# code behind?
Please excuse my ignorance, I'm completely out of my depth here!
If this is a progress image you are showing (seems so from the image name), then why would you want to do that server side? That will kind of defeat the whole purpose of a progress image. This seem like it belong on the client side, so keep it there.
Update
You don't need to use the code behind to render the script just to get the client id's. You can do something like this:
function ShowImage() {
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundImage = 'url(/images/vds/progress.gif)';
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundRepeat = 'no-repeat';
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundPosition = 'right';
}
function HideImage() {
document.getElementById('<%=tbxProdAC.ClientID%>')
.style.backgroundImage = 'none';
}
Here I use <%=tbxProdAC.ClientID%> to get the id of the control. This is a lot more readable then using the code behind to render the script.
I need some javascript to be run from the server side and this worked for me -
if (!this.ClientScript.IsStartupScriptRegistered("StartDown"))
{
string scriptString = #"alert(""some javascript"");location.href='MyPage.aspx';";
this.ClientScript.RegisterStartupScript(Page.GetType(), "StartDown", scriptString, true);
}
Hope this helps..

Categories