2016-10-14 26 views
1

この問題はこのサイトで何度も議論されていますが、私の問題は解決されませんでした。Asp.NETのC#からjavascript funtionを呼び出すことができません

以下の手順を実行しました。

1. JS関数を作成しました。

function showModal() { 
      alert("called"); 
     } 

2.追加

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager> 

3.

は.csファイル内のメソッドはファイルが作成.aspxのファイル内のスクリプトマネージャ

[System.Web.Services.WebMethod()] 
     [System.Web.Script.Services.ScriptMethod()] 
     protected void register_user(object sender, EventArgs e) 
     { 
      Page.ClientScript.RegisterStartupScript(this.GetType(), "showModal", "javascript:showModal(); ", true); 
      log.Debug("register_user is called"); 


     } 

しかし、それは呼び出していませんJS関数。

+0

@Div。それはちょうどタイプミスでした。 –

答えて

0

それが原因、あなたはjavascript関数閉じられていないのであるかもしれませ:

function showModal() { 
      alert("called"); 
} 

をORあなたもこれを試すことができます。

はあなたの次の行を置き換えますと

Page.ClientScript.RegisterStartupScript(this.GetType(), "showModal", "javascript:showModal(); ", true); 

Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "showModal(); ", true); // correct 
+0

私はあなたの提案に従って修正しました。まだ動かない。 –

0

非常に多くのものを混ぜている。

Code Behindのjavascriptをhtmlに追加したい場合は、これは、グローバルイベントPage_LoadまたはPreRenderに配置する必要があります。

Page.ClientScript.RegisterStartupScript(this.GetType(), "showModal", "YourJavascriptCode", true); 

あなたがあなたのボタンのクライアントのクリックでJavaScriptを実行したい場合は、応答

[System.Web.Services.WebMethod()] 
    [System.Web.Script.Services.ScriptMethod()] 
    public static string register_user(object sender, EventArgs e) 
    { 
     //you can return a class->Json 
     return stuff; 
    } 

を返す必要がありますAJAX呼び出しからのaspxのメソッドを呼び出したい場合。私はあなたがこれをしたいと思う!

YourButton.Attributes["onclick"]= "javaScriptFunction()"; 
    //if you want to not execute server side 
    YourButton.Attributes["onclick"]= "javaScriptFunction(); return false"; 

あなたのaspボタンにJavaScript機能を追加する最も簡単な方法です。

<asp:Button ID="RegisterBtn" runat="server" Text="Register" OnClientClick="showModal()" onclick="register_user"/> 
+0

ねえ。これはデモ用のJS関数です。私はそれが正常に実行された後にコードの行を追加する必要があります。 –

+0

@DKRあなたが何をしているのかわからない場合は、何百行ものコードを追加することができます。 – mybirthname

+0

を修正すると、1行も追加できません。ボタンのクリックで、pageloadではなく? –

0

まず、aspx.csからJs関数を呼び出すことは良い考えではないと思います。

とにかく、あなたのスニペットから、ちょうどこれに変更します。

Page.ClientScript.RegisterStartupScript(this.GetType(), "showModal", "showModal()", true); 

注意し3番目のパラメータで:"showModal()"

そしてまた、あなたのJS機能 "showModal()"、それはで動作しませんこのボタンをクリックしますか?私の仕事は何<input type="button" value="Submit" onclick="showModal();"/>

0

です:

の代わりに -

ScriptManager.RegisterStartupScript(this,GetType(), "Message", "showModal();", true); 

、それが働いていた - 私は追加

Page.ClientScript.RegisterStartupScript(this.GetType(), "showModal", "javascript:showModal(); ", true); 

0

名前空間を追加

System.Web.UIを使用します。

あなたの次の行に置き換えます

Page.ClientScript.RegisterStartupScript(this.GetType()、 "showModal"、 "ジャバスクリプト:showModal();"、true)を、

ScriptManager.RegisterStartupScriptと

(この、this.GetType()、 "メッセージ"、 "showModal();"、TRUE)。

正常に動作します。

関連する問題