繁体   English   中英

无法在Asp.NET中调用c#中的javascript函数

[英]Not able to call javascript funtion from c# in Asp.NET

在这个网站上多次讨论过这个问题,但我找不到解决问题的方法。

我已经执行了以下步骤。

1.创建了一个JS函数。

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

2.在.aspx文件中添加了一个脚本管理器

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

3.在.cs文件中创建了一个方法

 [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函数。

可能是因为,你还没有关闭你的javascript函数:

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

或者你也可以试试这个:

替换你的这一行:

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

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

你混合了很多东西。

如果你想将Code Behind的javascript添加到你的html中。 这应该位于某个全局事件Page_LoadPreRender

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

如果你想从AJAX调用aspx中调用方法,那应该返回响应

    [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;
    }

如果您想在客户端执行javascript,请单击按钮。 我想你想要这个!

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

这是将JavaScript函数添加到asp按钮的最简单方法。

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

首先,我不认为从aspx.cs调用Js函数是个好主意。

无论如何,从您的代码片段,只需更改为:

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

请注意第3个参数: "showModal()"

而且,你的JS函数“showModal()”,单击此按钮是否可以正常工作? <input type="button" value="Submit" onclick="showModal();"/>

对我有用的是:

代替 -

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

我补充说 -

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

它起作用了。

添加命名空间

使用System.Web.UI;

替换你的这一行:

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

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

它工作正常

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM