How to call java script from C# code? - c#

I have an Enable.js file that has an Enable() function. I want to call this Enable function from the C# codebehind. My .js file and c# file are in same application.
I have tried this, but it doesn't help me.
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "Enable(true)", true);

Try this:
ScriptManager.RegisterClientScriptInclude(
this,
typeof(Page),
"Enable-js",
ResolveClientUrl("~/scripts/Enable.js"));
ScriptManager.RegisterStartupScript(
this, GetType(), Guid.NewGuid().ToString(),
"Enable(True);", true);
http://msdn.microsoft.com/pt-br/library/bb337005.aspx

I could see "click" in your code. Hence, I assume that you need to click some button to call Enable(true) function inside Enable.js file
Follow these below steps:
Reference your Enable.js file inside <head> section like below.
<script src="Scripts/Enable.js" type="text/javascript"></script>
Enable.js file is given below:
function Enable(var){
alert(val)
}
To call on Enable() function on Button1's click event:
protected void Page_Load(object sender, EventArgs e){
Button1.Attributes.Add("OnClick", "return Enable('true');");
}
Let me know if you need some more help.

I wrote a nice little function for calling jquery or just general JS in C# based on some VB I saw a while ago.
public bool runJQueryCode(string message)
{
ScriptManager requestSM = ScriptManager.GetCurrent(Page);
if (requestSM != null && requestSM.IsInAsyncPostBack)
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), Guid.NewGuid().ToString(), getjQueryCode(message), true);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), getjQueryCode(message), true);
}
return true;
}
private string getjQueryCode(string jsCodetoRun)
{
string x = "";
x += "$(document).ready(function() {";
x += jsCodetoRun;
x += " });";
return x;
}
So you can just call runJqueryCode("alert('hey')");

You are making a mistake here:
Page.ClientScript.RegisterStartupScript(this.GetType(), "click", "Enable(true)", true);
The Enable(true) is not possible its literal string true that you're trying to pass as parameter.
You should try this way, so it may help.Its only a sample for understanding
string func = "showSuccessMessage('"+name+"');";
//Pass string as funcion in c#
This Link will explain calling javascript function with parameter from C# Code behind.
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",
"<script>test("+x+","+y+");</script>");

Related

button click event of code behind in javascript

i am trying to implement a button click event and trying to call it in my java script function without actually clicking the button.
protected void btn_hid_Click(object sender, EventArgs e) {
string fbid = tb_id.Text;
query = "select userid from users where fbid='" + fbid + "'";
ds = db.SelectDs(query);
}
now i want to call this function in javascript function as soon as page load occurs and java script is called.
function func() {
alert("hiden");
$(document).ready(function () {
control or simple html control
$("[id*='btn_hid']").click();
});
alert("hiden end");
}
but this is not happening.Could you please tell how to do it?
You can try with this code
btn_hid.Attributes.Add("onclick","return YourFunction()");
Nota : if your wish also register dynamically your script you can use
var script = "";
Page.RegisterStartupScript("YourkeyOfScript",script);
Nota : You can also use OnClientClick in your interface
Your code is right. but It may be some problem. you can try with the alternate code.
using the following line of code.
__doPostBack('<%= btn_hid.ClientID %>', '')

Javascript alert problem

I am trying to add an alert box so that the user can choose either Yes or No or Ok and Cancel, but it is not working correctly.I have to do a database check which is done in c sharp not just link that function to a button clicked event. It is my first time I am trying to do this. I am using visual studio 2010. I am not sure if my code is correct. Can anyone please guide me if I am mistaken.
private void AlertWithConfirmation()
{
Response.Write("<script language='javascript'>");
Response.Write("function onsub() ");
Response.Write("{ ");
Response.Write("return confirm(\"Are you sure?\")");
Response.Write("} ");
Response.Write("</script>");
}
This is my full C# Code:
protected void Import_Click(object sender, EventArgs e)
{
if (!Validation.ValidateDateFormat(dateField.Text))
{
errorMessageLabel.Text = "Invalid Date Format, for example: 1/1/2011 should be 01/01/2011";
}
else
{
//Validation to check if data is already imported
if (BusinessLayerHandler.isImported(dateField.Text) == false)
{
try
{
if (BusinessLayerHandler.isInProgress(dateField.Text)== true)
{
AlertWithConfirmation();
}
}
catch
{
//catch error
}
}
else if (BusinessLayerHandler.isImported(dateField.Text) == true)
{
Alert("That date was already imported");
}
}
your code is absolutely correct. only syntax error. just remove "\" before starting the double quotes in the line->
Response.Write("return confirm(\"Are you sure?\")");
replace with this line
Response.Write("return confirm("Are you sure?\")");
I don't see where you're calling the function. Why not have the function always on the page and dynamically add the function call to the button in the code behind?
Something like:
button.Attributes.Add("onclick", "onsub();");

Callback function?

I need to callback Javascript function in my code, but not firing. I am providing details what I am doing?.
I have input button in the page that calling javascript function. There I am loading another ProfilePic.aspx page. ProfilePic.aspx has FileUpload, OK and cancle button
<input type=button value="Change Image" onclick="javascript:SelectUserImage()" />
Javascript functions are
<script type="text/javascript">
function SelectUserImageCallback(ret) {
var imgId = 'ctl00_PlaceHolderMain_prof_imgUser';
var clearId = 'ctl00_PlaceHolderMain_prof_hidImageURL';
if (ret) {
if (ret == '__RESET__') {
document.getElementById(imgId).src = '\u002f_layouts\u002fimages\u002fno_pic.gif';
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = '';
document.getElementById(clearId).style.display = 'none';
}
else {
document.getElementById(imgId).onload = 'imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');';
document.getElementById(imgId).src = ret;
document.getElementById('ctl00_PlaceHolderMain_prof_hidImageURL').value = ret;
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 1);
setTimeout('imgResizeMax(\'ctl00_PlaceHolderMain_prof_imgUser\', 100);imgResizeTbl(\'ctl00_PlaceHolderMain_prof_imgUser\');', 100);
document.getElementById(clearId).style.display = '';
}
}
}
function SelectUserImage() {
var href = '\u002f_layouts\u002fProfilePic.aspx';
var features = 'resizable: yes; status: no; scroll: no; help: no; center: yes; dialogWidth: 460px; dialogHeight: 140px; width:460;height:240;menubar:no;directories:no;location:no;';
commonShowModalDialog(href, features, SelectUserImageCallback, null);
}
In the ProfilePic.aspx page once user click OK buttong. I am upload his pic with some logic then I am closing window with javascript
protected void btnOK_Click(Object sender, EventArgs e)
{
try
{
// My logic Here
Debug.WriteLine("Shared Pictures Save Ends: " + DateTime.Now);
Response.Write ("<script language =javascript>close();</script>");
Response.End();
}
catch (Exception exception)
{
LogMessage(exception.Message, EventLogEntryType.Error);
if (exception.Message.ToLower().Contains("blocked"))
errorDisplay.Text = "* This type of file has been blocked by the administrator, please try a different file.";
else
{
errorDisplay.Text = exception.Message;
}
}
}
My Question: I am able to close the window but, What ever I need to call callback function `SelectUserImageCallback' not firing. I need to call this method after OK button part execution done.
Are you closing the window before the callback executes? I've done that before. As an experiment, try commenting out the code that closes the window.
You may have to restructure your code so that the callback function closes the window when it's finished whatever it's doing.
Update: Sorry, I misunderstood the question. There was a lot of code and I didn't read it all. I thought the call back was in the dialog page, but it looks like it's in the main page. I'm not familiar with commonShowModalDialog(), but it looks like it may have something to do with SharePoint. Do you have any documentation on that method? I found this discussion that makes it look like there's a special way to return a value from the dialog box. It may be that your callback isn't being called because you're not closing the window the right way. (That's a total guess on my part.)
Good luck.

calling javascript from codebehind or dopastback in javascript

i have a button1_click() function which runs on page load,,now i want to call this function from javascript,,for that purpose i need to do dopostback in javascript,,can nyone tell how can i do that..as u can see my pageload function that button1_click() runs on postback
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int l = files.Length;
Button1.Attributes.Add("onclick", " alertMe("+ l.ToString() +");");
}
Button1_Click();
}
my javascript code :
function alertMe(len)
{
if(len>3)
//do postback(post back will run Button1_click function)
else
alert('Hello');
}
This is a helpful link
From the article:
"
Calling postback event from Javascript
There may be some scenario where you may want to explicitly postback to the server using some clientside javascript. It is pretty simple to do this.
ASP.NET already creates a client side javascript method as shown below to support Postbacks for the web controls:
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
"
one way would be to use an actual asp:Button and utilize the OnClientClick event...
<asp:Button id="myButton" runat="Server" OnClick="Button1_Click" OnClientClick="alertMe();" />
function alertMe()
{
if (this.len>3)
{
return true;
}
else
{
return false;
}
}
if alertMe returns true, the the postback to the server will occur, if it returns false,
it won't.
here is a link to more details on the OnClientClick event.
It looks like you want to use ajax to call this server method. You can use ajax.net to do this. Obviously as a result it will not be postback.
Have a look here for examples
Possibly this:
function alertMe(len)
{
if(len>3)
//do postback(post back will run Button1_click function)
alertMe(len);
else
alert('Hello');
}
I would always try to avoid inline js though

How can I call a javascript function from inside a method?

I am inside of...
public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
Some code...
and after "some code" I want to trigger
[WebMethod]
public static void DoSome()
{
}
Which triggers some javascript. Is this possible?
Ok, switch methods here. I was able to call dosome(); which fired but did not trigger the javascript. I have tried to use the registerstartupscript method but don't fully understand how to implement it. Here's what I tried:
public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
...my C# code to perform on dropdown selection...
//now I want to trigger some javascript...
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}
}
}
I got the registerstartupscript code from an msdn example. Clearly I am not implementing it correctly. Currently vs says "An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.ClientScript.get' refering to the piece of code "Page.Clientscript;" Thanks.
I'm not sure I fully understand the sequence of what you are trying to do, what's client-side and what's not....
However, you could add a Start-up javascript method to the page which would then call the WebMethod. When calling a WebMethod via javascript, you can add a call-back function, which would then be called when the WebMethod returns.
If you add a ScriptManager tag on your page, you can call WebMethods defined in the page via Javascript.
<asp:ScriptManager ID="scriptManager1"
runat="server" EnablePageMethods="true" />
From the Page_Load function you can add a call to your WebMethod..
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"callDoSome",
"PageMethods.DoSome(Callback_Function, null)",
true);
Callback_Function represents a javascript function that will be executed after the WebMethod is called...
<script language="javascript" type="text/javascript">
function Callback_Function(result, context) {
alert('WebMethod was called');
}
</script>
EDIT:
Found this link for Web ADF controls. Is this what you are using??
From that page, it looks like something like this will do a javascript callback.
public void ServerAction(ToolbarItemInfo info) {
string jsfunction = "alert('Hello');";
Map mapctrl = (Map)info.BuddyControls[0];
CallbackResult cr = new CallbackResult(null, null, "javascript", jsfunction);
mapctrl.CallbackResults.Add(cr);
}
If the above is how you are calling RegisterStartupScript, it won't work because you don't have a reference to the "Page" object.
bgchange in your example extends Object (assuming IMapServerDropDownBoxAction is an interface), which means that there is no Page instance for you to reference.
This you did the exact same thing from a Asp.Net Page or UserControl, it would work, because Page would be a valid reference.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"helloworldpopup",
"alert('hello world');",
true);
}
}
You cannot call methods within a browser directly from the server. You can, however, add javascript functions to the response that will execute methods within the browser.
Within the ServerAction method, do the following
string script = "<script language='javascript'>\n";
script += "javascriptFunctionHere();\n";
script += "</script>";
Page.RegisterStartupScript("ForceClientToCallServerMethod", script);
More info here
hmmm... the question changed dramatically since my original answer.
Now I think the answer is no. But I might be wrong.

Categories