在Javascript中使用C#方法

Using C# Method in Javascript

本文关键字:方法 Javascript      更新时间:2023-09-26

我的aspx页面:

<asp:TableCell>
<asp:TextBox ID="tbFirstName" ClientIDMode="Static" runat="server" onblur="javascript:CheckFirstNameInput(this)"> 
        </asp:TextBox>
    </asp:TableCell>

我的C#类

[ScriptService()]
public static class InputChecks
{
[WebMethod()]
    [ScriptMethod()]
    public static bool CheckForLettersSpacesStripes(string input)
    {  //SomeCode   }}

我的主页

<asp:ScriptManager runat="server" ID="smScriptManager" EnablePageMethods="true">
    <Scripts>
    <!-- And some standard imported scripts -->
        <asp:ScriptReference Path="~/Resources/JavaScriptFunctions.js" />
    </Scripts>
</asp:ScriptManager>    

正如你可能注意到的,我的想法是在这里导入一个javascript,它工作得很好。通过一个警报和几个console.log之类的东西进行了测试。但我无法达到C#方法,我使用了一些东西。我使用了一个ajax调用:

    function CheckFirstNameInput(InputElement)
{
    var Input = InputElement.value;
    console.log(Input);
    $.ajax({
        url: "Test",
        data: "{input : " + Input + "}",
        success: function(response)
        {
            alert(response.url);
        }
    });
}

但我也只是使用了PageMethods。以上都不起作用,我试着把脚本管理器放在aspx页面而不是母版页面中,但没有成功。我完全没有想法,也没有在网上找到任何新东西。所以,有人知道答案吗?我会永远感激这个答案,它让我摆脱了这个烦人的负担。

您需要更改URL

将url:"Test"更改为url:"Application Path/CheckForLettersSpacesStripes",

或者使用PageMethods 尝试另一种方法

你不需要任何行,只需尝试此代码而不是你的代码

PageMethods.CheckForLettersSpacesStripes(input);

参考