Calling javascript in csharp class - c#

I have a class. There is only deleteRecord function
protected virtual void DeleteRecord
{
if(..)
{}
else(..)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "<script language='javascript'>alert('Are you sure?')</script>", true);
}
}
I want to show javascript message. But I think I made a mistake.
How can I do it?

You've added true to the last parameter on Page.ClientScript.RegisterStartupScript which is addScriptTags. See http://msdn.microsoft.com/en-us/library/z9h4dk8y.aspx
Therefore you have essentially added <script> within a <script>
Try this:
Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Are you sure?')", true);
Also ensure the key parameter is unique to the page. If you already have a StartupScript with the key of "Alert" then this can also stop it from calling the JavaScript code.

I created this static class that I can call from any web page: (I use AJAX Toolkit for script manager, but you can use the default one in ASP.NET as well)
public static class ClientJS {
public static void send(string js) {
Page page = HttpContext.Current.Handler as Page;
ToolkitScriptManager.RegisterStartupScript(page, page.GetType(), Guid.NewGuid().ToString(), "setTimeout(function(){" + js + "},1);", true);
}
}
Use it like so:
ClientJS.send("alert('Are you sure?');");

Related

How to dynamically generate and send jQuery to the webpage from C# AND have it work

So, I am dynamically generating jQuery using C# and sending it to the webpage.
The problem is it appears to be generating correct jQuery according to the file and according to Js Fiddle but it does not actually work on the page.
The jsFiddle is here http://jsfiddle.net/ER2hE/
Now I looked up how to send javacript to the website. It should work like this.
http://msdn.microsoft.com/en-us/library/bb359558.aspx
and my code which does that is this method
private void sendScript(string script)
{
const string someScript = "alertMe";
//send the built script to the website.
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), someScript, script, true);
}
This is super simple it has worked for other pieces of code calling. But it has not for this instance.
The code that calls it is this in my C#
private void populateGroups()
{
//this generates correct javascript according to the file and JS fiddle but unfortunately doees not work.
string splitme = "USE ACES SELECT GroupName, GroupID FROM PrimaryGroup ORDER BY GroupName";
DataTable dt = fillDataTable(splitme);
string script = "";
foreach (DataRow dr in dt.Rows)
{
//add the locations to the <select> box
script += " $('#groupList').append('<option value=\" " + dr.ItemArray[1].ToString() + " \"> " + dr.ItemArray[0].ToString() + " </option>'); ";
}
sendScript(script);
JSErrorLog(script, "GROUPS");
}
The whole thing is being called on startup
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack == false)
{
populateMakes();
populateLocation();
populateGroups();
}
}
The jQuery its generating also works in JSFiddle I am pulling this from a method that writes the javascript it generates in a method calling here is the fiddle JSErrorLog.
http://jsfiddle.net/ER2hE/
Oh and my html in my aspx file looks like this
<div class="row2">
<span>Group</span>
<select id="groupList" multiple="multiple" onclick="setGroups()" class="normalsize">
</select>
</div>
I believe that is everything. I just want my stuff to work. I am willing to post any additional code, just ask. If you have an idea as to why its not working, let me know.
When does it actually execute that code? Before or after the element with id "groupList" exists in the DOM? My guess is before.
Solution? Wrap your code inside a document.ready handler.
jQuery(function($) {
$('#groupList').append('<option value=" 46 "> AC Units </option>');
// etc etc
});
Return simple string js code. And run it with eval()

Is there a way to drop static declaration from page method?

For a site I'm developing I have two html buttons, not ASP because I do not want them to postback. For the submit button I am calling a javascript function that implements PageMethods to call a C# method from the codebehind. Here is the code for the buttons and the javascript.
<fieldset id="Fieldset">
<button onclick="SendForm();">Send</button>
<button onclick="CancelForm();">Cancel</button>
</fieldset>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" EnablePartialRendering="true" runat="server" />
<script type="text/javascript">
function SendForm() {
var email = $get("txtEmail").value;
PageMethods.SendForm(email, OnSucceeded, OnFailed);
}
function OnSucceeded() {
$get("Fieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
alert(error.get_message());
}
</script>
The codebehind method shown here:
[WebMethod]
public static void SendForm(string email)
{
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
else
{
if (IsValidEmailAddress(email))
{
bool[] desc = new bool[14];
bool[] local = new bool[14];
bool[] other = new bool[14];
for (int i = 1; i <= 14; i++)
{
desc[i] = ((CheckBox)Page.FindControl("chkDesc" + i.ToString())).Checked;
local[i] = ((CheckBox)Page.FindControl("chkLocal" + i.ToString())).Checked;
other[i] = ((CheckBox)Page.FindControl("chkOther" + i.ToString())).Checked;
/* Do stuff here */
}
}
else
{
throw new Exception("You must supply a valid email address.");
}
}
}
does not work unless it is declared as static. Declaring it as static blocks me from checking the checkboxes on the page because it generates a "An object reference is required for the non-static field, method, or property" error. So my problem can be fixed from either of two directions. A) Is there a way I can have this method work without declaring it as static? B) How do I check the checkboxes if the method is static.
It has to be static, no way around that; But you can access the Page like this
Page page = HttpContext.Current.Handler as Page;
and do FindControl on this page instance.
desc[i] = ((CheckBox)page.FindControl("chkDesc" + i.ToString())).Checked;
Page Methods are a special case of the legacy ASMX web service technology. They allow you to place the service in the codebehind class for the page, and keep you from needing a separate project for the service.
But they will never be able to access anything on the page itself. You'll have to do that from the client side, and pass the values of the check boxes to the service.
If you need to check the checkboxes, then you need to either use an UpdatePanel to do your AJAX stuff, or return something from your page method (ideally a string) and check the checkboxes based on what's returned in javascript on client.

calling javascript from c#

I need to use the javascript functions to show and hide an element on my page, but calling it from within a C# method. Is this possible?
EDIT : I tried RegisterStartupScript (see below) but this did not hide the elements as I had hoped :
HidePopup("CompanyHQSetup", "$('#<%=DivDataProvider.ClientID %>').hide();$('#<%=modalOverlay.ClientID %>').hide();");
private void HidePopup(string Key, string jscript)
{
string str = "";
str += "<script language='javascript'>";
str += jscript;
str += "</script>";
RegisterStartupScript(Key, jscript);
}
EDIT : Got around this by using a hidden field boolean to determine whether or not to hide or show the elements
Yes, check out RegisterClientScriptBlock.
Here's a snippet taken from that link:
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client script on the page.
String csName = "ButtonClickScript";
Type csType = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(csType, csName))
{
StringBuilder csText = new StringBuilder();
csText.Append("<script type=\"text/javascript\"> function DoClick() {");
csText.Append("Form1.Message.value='Text from client script.'} </");
csText.Append("script>");
cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
}
}
One is server side, the other is client side. They can pass variables to each other (Javascript to ASP would be via forms/querystring/cookies and ASP to JS done via response.writing variables), but they can't directly interact.
you can use page.RegisterClientScript method to do that go on the following url
http://msdn.microsoft.com/en-us/library/system.web.ui.page.registerclientscriptblock.aspx
and give it a try
Javascript is client side, c# is server side. You can't call javascript directly from C#. Take a look at Comet though, it will show you how you can push data from the HTTP server to the webpage.

Register javascript inside User Control using C#

I want to call javascript function from User Control using C#. For that i am trying to use
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "javascript:ShowPopup('Select a row to rate');", true);
but it is not working for me. This works fine on the page. Can some one help me out how can i call javascript function at runtime using C#.
Thanks,
Try this.GetType() instead of typeof(string):
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertbox", "ShowPopup('Select a row to rate');", true);
The following is taken from working code, showing script being registered to fire from an asynchronous postback in an UpdatePanel.
ScriptManager.RegisterStartupScript( this.upnl, this.upnl.GetType(), Guid.NewGuid().ToString(), "alert('test');", true );
If your code is not executed from inside an UpdatePanel, it still should not be typeof(string); you should use the type of some container (typically the control itself).
Type: The type of the client script block. This parameter is
usually specified by using the typeof
operator (C#) or the GetType operator
(Visual Basic) to retrieve the type of
the control that is registering the
script.
Im not sure if this is the best way to do it but for my user controls that use javascript i have a public string property on the user control and register it in the page.
// sudo code
eg.
UserControl
{
public bool CustomBool
{
get
{
//logic
return value;
}
}
public string Javascript
{
get { return "javascript...."; }
}
}
in page
{
page load()
{
if (Usercontrol.CustomBool)
{
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", UserControl.Javascript, true);
}
}
}
The downside for this is you have to remember to register the scripts on the page. it does work though
Try it without the "javascript:" in the script string:
ScriptManager.RegisterStartupScript(this, typeof(string), "alertbox", "ShowPopup('Select a row to rate');", true);
I find that the string given is embedded literally, so it's necessary to enclose it in a suitabie <script type='text/javascript' language='javascript'> and </script>

Calling JavaScript function from code beind (c#) catch block

I am trying to call a JavaScript function from my ascx control code behind in the catch block.
I have tried the below two ways but they don't seem to work.
Page.ClientScript.RegisterClientScriptBlock(typeof(string), "script", "test();", true);
ScriptManager.RegisterStartupScript(Page, GetType(), "err_msg", "alert('error');", true);
The function is called if I place the code Under "PageLoad" but doesn't get called when placed in catch block.Should I do any different to call a JavaScript function from catch block. Please suggest.
Thanks
Have you tried this?
Page.ClientScript.RegisterStartupScript(typeof(string), "script", "test();", true);
I cant recall off the top of my head if that is equivalent to the ScriptManager option in the question.
Also you need to make sure that the "script key" value you are passing in is unique otherwise asp.net will discard all but the first instance of the registered script with the same key.
might want to try this:
.cs
public String ScriptToRun = "test();";
.aspx
$(document).ready(function() {<%=ScriptToRun %>}); //or you can register event to document mannually
Remember that whatever you done in backend is going to generate HTML, Css& javascript to browser.
update:
I tried the following code, it works in my case. could you please provide more detail?
.cs
public String script = "";
protected void Page_Load(object sender, EventArgs e)
{
throwExcep();
}
private void throwExcep()
{
try
{
throw new NotImplementedException();
}
catch (Exception e)
{
script = "console.log('exception throws from backend message: ["+e.Message+"]')";
}
}
.aspx:
<script>
$(document).ready(function(){
<%=script %>
});
</script>
Javascript does not like at all special characters and NewLine (\r\n) characters. Replace all of those and it will work.
Example:
string test = msgError.Replace("'", "");
test = Server.HtmlEncode(test).Replace(Environment.NewLine, "<br />");
Page.ClientScript.RegisterStartupScript(
typeof(string),
"MyKeyCatch",
//script,
"showErrorMessage('"+test+"');",
true);
What is the catch block for and where is it?
If code in a catch block is executed it usually means that something failed, maybe that failure also is the reason the JS call does not go through.

Categories

Resources