2016-12-05 34 views
1

asp.NETとjQueryでajaxを使用する方法を学習しており、ブラウザで簡単なファイルエディタをシミュレートしようとしています。これまでのところ、WebMethodsを使用してajaxとjQueryを使用してロードされているファイルのリストがあります。ボタンをクリックしてファイルをロードするためにその機能を複製しようとすると、無効なポストバックの例外が発生します。私はボタンにjQueryをリンクし、入力値をデバッグする多数の方法を試してみましたが、それは遅くなっていると私は単純に問題のあるDを見つけるように見えることはできません。ASP.NET "asp:button"のポストバックまたはコールバック引数がJQuery POSTでクリックされない

マイビュー:

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

FileEditor.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; 
} 

EXCEP

[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 

この問題に対するアドバイス/修正は素晴らしいものです。

+1

ボタンをクリックすると、WebEditor.aspx/GetFileListの "webメソッドを呼び出しているようですが、パラメータはありませんが、パラメータとして' data:JSON.stringify({selectedFile :selectedFile}) '最初の呼び出しにそのようなパラメータがありません。' data: '{}' '。なぜこれが必要ですか? – Aruna

+0

下記の私の更新された回答を見ることができます。 – Aruna

答えて

1

更新は:あなたのコメントを1として、私はこれをさらに調査していると完全にダウンし、以下に記載されているよう3の問題を見ることができます。

すべての3つの問題が修正されたら、作成したサンプルアプリでこれを確認できます。

だから私はこれもあなたのために100%うまくいくと思います。

問題1

あなたLoadFile機能では、私はあなたがLoadFileContentsを呼び出す必要が想定していますが、任意のパラメータは、Webメソッドの背後にあるコードで定義されていないはずパラメータdata: JSON.stringify({ selectedFile: selectedFile })GetFileListを呼び出しています。

これを以下のようにWebEditor.aspx/LoadFileContentsに変更することができます。

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

問題2

WebMethodpublic static string LoadFileContents(string fileName)fileNameとしてパラメータ名を持つように、以下のパラメータ名は、このような、

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

発行3と同じでなければなりません:

そしてfボタン<asp:Buttonがクライアント側でレンダリングされるとき、それは「送信」ボタンtype="submit"としてレンダリングされるため、これは前述のエラーで再び終了するフォーム送信を呼び出します。だから、このフォームの提出を防ぐために、あなたは、このため、最終的なfunctionは以下のようになり

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

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); 
    } 
+0

これは明らかに答えが必要だったようですが、それは間違いなく解決された問題でしたが、まだエラーが発生します。 –

+0

ロードファイルの内容メソッドにロードしてデータをロードしているようですが、コールバックが完了した後、再びこのエラーメッセージが表示されます。 –

+0

これ以上の助けを借りれば幸いです –

1

あなたLoadFileContents内WebMethod属性はPage.IsPostback溶液(http://net-informations.com/faq/asp/ispostback.htm)を試してみてください。

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

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

WebMethodsが静的であるため、Page.IsPostBackにアクセスできません –

関連する問題