I am using the below client script in aspx code behind to call a javascript function. But the below client script in public static method so i got the error in registerstartupscript first argument.My older post is here Call non-static function from static function
If any one have a possible solutions please post..
Page.ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "from_bill_tab();");
Try this:
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError",
"<script type='text/javascript'>alert('Error !!!');</script>");
I know this is an old question.I am answering this to help new users who come across this question.
To use clientscript inside a static method pass the Page object as a parameter to your static method
protected void Page_Load(object sender, EventArgs e)
{
LoadJavascript(Page);
}
public static void LoadJavascript( Page page)
{
page.ClientScript.RegisterStartupScript(page.GetType(), "alert", "<script>alert('Hai');</script>");
}
Related
I have a MVVVM app with a view model that uses Hammock .
I call my Get2 function in the code behind my main page like this:
private void List2_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
if (List2.SelectedItem != null)
{
((MainPageViewModel)DataContext).Get2();
NavigationService.Navigate(new Uri("/Page3.xaml", UriKind.Relative));
}
}
Here is my Get2 Function:
public void Get2()
{
[...]
restClient.BeginRequest(restRequest, Get2CallBack);
}
private void GetListStatusesCallBack(RestRequest Request, RestResponse Response, object Obj)
{
[...]
}
But what happens at the end of my Get2() function is that instead of reaching the callback function just after , it goes back to my MainPage code behind, executs the NavigationService.Navigate(new Uri("/Page3.xaml", UriKind.Relative));
, quits the List2_SelectionChanged_1 and then reaches the CallBack function finally .
How come my CallBack Function is not reached just after Get2() ?
I would like the CallBack to be reached before the Navigation Event,
Your method should be a Synchronous call. The behavior that you are describing requires the use of a Synchronous call.
However, looking at your code, the call looks to be async (BeginRequest).
Perhaps if you could post more details about the variable restClient (Datatype, intended usage etc.) it would be helpful.
Alternatively, you could try having this line in the call back method
NavigationService.Navigate(new Uri("/Page3.xaml", UriKind.Relative));
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>");
Ok so i'm using this piece of AJAX code
xhr2 = new XMLHttpRequest();
xhr2.open('POST', '/AllPoints.aspx', false);
xhr2.setRequestHeader('kml_file', path);
And what I'm doing server side is this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Request.Headers["kml_file"]))
{
DataTable dt = GetDataSet().Tables[0];
CBList_Pontos_Repetidos.DataSource = dt;
CBList_Pontos_Repetidos.DataTextField = dt.Columns[1].ToString();
CBList_Pontos_Repetidos.DataValueField = dt.Columns[0].ToString();
CBList_Pontos_Repetidos.DataBind();
}
}
}
And everything runs fine and by debugging I can see all the code is being executed, problem is, it's all server side and there's no actual postback, async or not, so nothing is shown client-side, I can only see it server side.
I've been around and around this and I can't seem to figure out the solution, any help?
PS: I've edited all the unnecessary strings of code so you can understand it better.
Thanks in advance.
I would have a look at accessing asp.net page methods through ajax. Here's a helpful link
I have active-x class written in c# which is multi-threaded. I need to call javascript from my activeX. I tried it by Microsoft.mshtml .
/*JS
function do_Print() {
control.setPage(this);
control.scriptPrint();
}
function report_back(report){
alert("Report:"+report);
}
C#
public void setPage(mshtml.HTMLWindow2Class JSFile) {
window = JSFile;
}
public void scriptPrint(){
window.execScript("report_back('Printing complete!')", "JScript");
}
*/
But its throwing exception
"unable to cast COM object of type
'mshtml.HTMLWindow2Class' to interface
type 'mshtml.DispHTMLWindow2'"
Is there another way round. I am able to call active-x function from java script but vice versa still got above exception. Any idea for multi-threaded c# active-x calling javascript function ???
you can access html like this
private void MyControl_Load(object sender, EventArgs e)
{
if (this.Site != null)
{
htmldoc = (HtmlDocument)this.Site.GetService(typeof(HtmlDocument));
}
}
then on any button click on our C# control invoke method to click html button
HtmlElement setCLIButton = htmldoc.GetElementById("searchButton");
setCLIButton.InvokeMember("onClick");
by this way you can call your javacsript function hope it will help someone.
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.