javascript - "asp:button"上的 ASP.NET 无效回发或回调参数单击 JQuery POST

标签 javascript c# jquery asp.net ajax

我正在学习如何将 ajax 与 asp.NET 和 jQuery 结合使用,并尝试在浏览器中模拟一个简单的文件编辑器。到目前为止,我有一个通过 WebMethods 使用 ajax 和 jQuery 加载的文件列表。当我尝试为单击按钮复制该功能以加载文件时,我收到无效回发的异常。我已经尝试了多种方法将 jQuery 链接到按钮并调试传入的值,但是已经晚了,我似乎根本找不到问题 D:

我的看法:

<form id="textform" runat="server">
<div>
    <asp:DropDownList ID="ddlSelectFile" runat="server">
        <asp:ListItem Text="Select a file..." Value="" />
    </asp:DropDownList>
    <asp:Button ID="btnLoadFile" runat="server" Text="Load File" />
    <asp:Button ID="btnSaveFile" runat="server" Text="Save File" />
    <br />
    <asp:TextBox ID="txtFileEditor" runat="server" TextMode="MultiLine" Width="100%" Height="100%" />
</div>
</form>

代码隐藏:

public partial class WebEditor : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static List<string> GetFileList()
    {
        string path = HostingEnvironment.ApplicationPhysicalPath + "\\Files";
        List<string> files = new List<string>();

        foreach(string filePath in Directory.GetFiles(path))
        {
            string fileName = Path.GetFileName(filePath);
            files.Add(fileName);
        }

        return files;
    }

    [WebMethod]
    public static string LoadFileContents(string fileName)
    {
        string fileContents = string.Empty;
        string path = HostingEnvironment.ApplicationPhysicalPath + "\\Files\\" + fileName;

        if (File.Exists(path))
        {
            fileContents = File.ReadAllText(path);
        }

        return fileContents;
    }
}

文件编辑器.js:

$(document).ready(function () {
$("#btnLoadFile").on('click', LoadFile);

$.ajax({
    type: "POST",
    url: "WebEditor.aspx/GetFileList",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnFileListReceived,
    failure: function (response) {
        alert(response.d);
    },
    error: function (response) {
        alert(response.d);
    }
});

function OnFileListReceived(response) {
    var files = response.d;
    var fileList = $("#ddlSelectFile");

    $(files).each(function (val, text) {
        fileList.append($('<option></option>').val(text).html(text));
    });
}

});


function LoadFile() {
var selectedFile = $("#ddlSelectFile").val();
$.ajax({
    type: "POST",
    url: "WebEditor.aspx/GetFileList",
    data: JSON.stringify({ selectedFile: selectedFile }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnFileContentsReceived,
    failure: function (response) {
        alert(response.d);
    },
    error: function (response) {
        alert(response.d);
    }
});
}


function OnFileContentsReceived(response) {
    var fileContents = response.d;
}

抛出的异常信息:

[ArgumentException: Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
   System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +9748914
   System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
   System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) +64
   System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +18
   System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +457
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1833

对此问题的任何建议/修复都会很棒。

最佳答案

更新:根据您的评论,我已经对此进行了进一步调查,可以看到 3 个问题,如下所列。

一旦所有 3 个问题都得到解决,我就可以在我创建的示例应用程序中检查它是否正常工作。

所以我希望这对您也 100% 有用。

问题 1:

在你的LoadFile函数,我假设你应该调用 LoadFileContents但你调用GetFileList带有参数 data: JSON.stringify({ selectedFile: selectedFile })它不应该在 web 方法的代码中定义任何参数。

所以你可以把它改成WebEditor.aspx/LoadFileContents如下所示。

$.ajax({
        type: "POST",
        url: "WebEditor.aspx/LoadFileContents"
        ....
});

问题 2:

作为 WebMethod参数名称为 fileNamepublic static string LoadFileContents(string fileName) ,下面的参数名应该和这个一样,

data: JSON.stringify({ fileName: selectedFile })

问题 3:

最后,当按钮 <asp:Button在客户端呈现,呈现为“提交”按钮 type="submit"因此,这是调用一个表单提交,该表单再次以上述错误结束。因此,为了防止提交此表单,您可以添加以下行,

function LoadFile(e) {
   e.preventDefault();
   ....
}

因此,您的最终 function变成如下,

   function LoadFile(e) {
        e.preventDefault();
        var selectedFile = $("#ddlSelectFile").val();
        $.ajax({
            type: "POST",
            url: "WebEditor.aspx/LoadFileContents",
            data: JSON.stringify({ fileName: selectedFile }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnFileContentsReceived,
            failure: function (response) {
                alert(response.d);
            },
            error: function (response) {
                alert(response.d);
            }
        });
    }

然后我用下面的代码在文本框中呈现文件内容,

    function OnFileContentsReceived(response) {
        var fileContents = response.d;
        $("#txtFileEditor").val(fileContents);
    } 

关于javascript - "asp:button"上的 ASP.NET 无效回发或回调参数单击 JQuery POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40968891/

相关文章:

javascript - meteor onConnection 客户端 Hook ?

php - jQuery 自动完成功能无法正常工作

c# - NAT 在其表中保留 TCP 转换字段多长时间?

c# - 在 C# 中将查询字符串序列化为 Json - 值不显示,仅显示键。为什么?

c# - 正则表达式解析 C# 源代码以查找所有字符串

javascript - 跨域请求不适用于 Safari 中的 SoundCloud

javascript - 根据容器高度 : What am I doing wrong? 创建动态字体大小

javascript - 保留下拉选择吗?我究竟做错了什么?

javascript - 将今天日期设置为kendo datepicker

php - 使用 jquery 突出显示弹出部分