あなたが質問したことは必ずしも必要ではありませんが、通常のWebフォームページにあるサーバー側のメソッドにJSON呼び出しを行う場合は、「遅い道」をとっています。
私はHttpHandler
を提案します。あなたの標準的なWebフォームとは異なります。ページのライフサイクルがないため(速くてすばらしい)、コードの分離や再利用性が大幅に向上します。
"Generic Handler"プロジェクトに新しいアイテムを追加してください。これにより、新しい.ashxファイルが作成されます。 IHttpHandler
を実装するクラスの主なメソッドはProcessRequest
です。あなたのAJAX呼び出しで
public void ProcessRequest (HttpContext context) {
Debug.Print("Hello");
return;
//the following code should be used to return json to the ajax method
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
変更にURLを、それはそれを行う必要があります。だからあなたの元の質問からコードを使用します。
$.ajax({
type: 'GET', //change this to POST if you want to pass a json object to the server side method (works in unison with the `dataType` property)
contentType: "application/json; charset=utf-8",
url: 'Handlers/RunTestMethod.ashx',
async: true, //notice I set async to true so your page does not "freeze" while the ajax call is being made
dataType: "json", //if needed, this property allows you to receive json back from the server side method (works in unison with the `type` property)
success: function (response) {
alert("SUCCESS");
}
});
考慮すべきもう一つの小さな点、あなたはハンドラのコード自体内からSessionオブジェクトにアクセスする必要がある場合:RunTestMethod.ashxが作成したばかりのIHTTPハンドラの名前ですJavaScriptは、このようになります。あなたが成功関数に渡された応答に文字列が含まれないのtestMethodから文字列を返す場合
public class GetFileHandler : IHttpHandler, IRequiresSessionState
:、
IRequiresSessionState
インタフェースを継承することを確認してください? – Calum@カルマ - いいえ。私の成功関数で「警告(応答);」と言うと、私は実際のページのHTMLを取得します。私の前提は、TestMethodではなく、「Page_Load」の「応答」を私に与えるからです。 – Hill