[英]How can I call a javascript function from inside a method?
我在里面......
public class bgchange : IMapServerDropDownBoxAction
{
void IServerAction.ServerAction(ToolbarItemInfo info)
{
Some code...
並且在“一些代碼”之后我想觸發
[WebMethod]
public static void DoSome()
{
}
哪個觸發了一些javascript。 這可能嗎?
好的,在這里切換方法。 我能夠調用dosome(); 雖然解雇但沒有觸發javascript。 我曾嘗試使用registerstartupscript方法,但不完全了解如何實現它。 這是我試過的:
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);
}
}
}
我從msdn示例中獲得了registertartupscript代碼。 顯然我沒有正確實現它。 目前vs說“非靜態字段,方法或屬性'System.Web.UI.Page.ClientScript.get'需要一個對象引用,引用一段代碼”Page.Clientscript;“謝謝。
我不確定我是否完全理解你要做什么的順序,什么是客戶端,什么不是......
但是,您可以向頁面添加一個啟動javascript方法,然后調用WebMethod。 通過javascript調用WebMethod時,可以添加一個回調函數,然后在WebMethod返回時調用該函數。
如果在頁面上添加ScriptManager標記,則可以通過Javascript調用頁面中定義的WebMethods。
<asp:ScriptManager ID="scriptManager1"
runat="server" EnablePageMethods="true" />
從Page_Load函數中,您可以添加對WebMethod的調用。
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"callDoSome",
"PageMethods.DoSome(Callback_Function, null)",
true);
Callback_Function表示將在調用WebMethod后執行的javascript函數...
<script language="javascript" type="text/javascript">
function Callback_Function(result, context) {
alert('WebMethod was called');
}
</script>
編輯:
找到此鏈接用於Web ADF控件 。 這是你正在使用的??
從該頁面看起來像這樣的東西會做一個javascript回調。
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);
}
如果以上是調用RegisterStartupScript的方法,那么它將無效,因為您沒有對“Page”對象的引用。
您的示例中的bgchange擴展了Object(假設IMapServerDropDownBoxAction是一個接口),這意味着您沒有可供引用的Page實例。
你從Asp.Net頁面或UserControl做了完全相同的事情,它會工作,因為Page將是一個有效的參考。
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);
}
}
您無法直接從服務器調用瀏覽器中的方法。 但是,您可以將javascript函數添加到將在瀏覽器中執行方法的響應中。
在ServerAction方法中,執行以下操作
string script = "<script language='javascript'>\n";
script += "javascriptFunctionHere();\n";
script += "</script>";
Page.RegisterStartupScript("ForceClientToCallServerMethod", script);
嗯......自從我的原始答案以來,問題發生了巨大的變化。
現在我認為答案是否定的。 但我可能錯了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.