応答のために複数の情報を返す必要があります。幸いなことに、これは JSON を使用して簡単に行うことができます。応答タイプが json であると jQuery に伝えれば、jQuery が自動的に処理してくれます。ajax コールバック関数に取得するオブジェクトには、必要なすべてのデータがさまざまなプロパティとして含まれます。
各 ajax 呼び出しで「成功」または「失敗」のステータス コードと、エラーのコレクションを返す習慣を身につけることをお勧めします。 私が言いたいことの詳細については、この素晴らしいブログ投稿を参照してください。
この理由は、サーバーが実際にリクエストを処理できず、失敗の http ステータス コードを返さない限り、ajax 呼び出しは常に基本的に「成功」するためです。要求の結果が検証エラーのようなものであるにもかかわらず、サーバーが何らかのテキスト応答を返す場合、アプリケーション操作が失敗したとしても、ajax 呼び出しは成功したと見なされます。
したがって、アクション メソッドで、アクション結果で html データを返す代わりに、次のようなオブジェクトを返した場合:
public class AjaxResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="AjaxResponse"/> class.
/// This creates an AjaxResponse that by default indicates SUCCESS.
/// </summary>
public AjaxResponse()
{
Success = true;
Data = new List<object>();
}
/// <summary>
/// Initializes a new instance of the <see cref="AjaxResponse"/> class.
/// This creates an AjaxResponse that indicates FAILURE.
/// </summary>
/// <param name="exception">The exception.</param>
public AjaxResponse(Exception exception)
: this()
{
Success = false;
Errors = new [] { exception.Message };
}
/// <summary>
/// Initializes a new instance of the <see cref="AjaxResponse"/> class.
/// This creates an AjaxResponse that indicates SUCCESS.
/// </summary>
/// <param name="data">The data.</param>
public AjaxResponse(object data)
: this()
{
Data = data;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="AjaxResponse"/> is success.
/// </summary>
/// <value><c>true</c> if success; otherwise, <c>false</c>.</value>
public bool Success
{
get; set;
}
/// <summary>
/// Gets or sets the data.
/// </summary>
/// <value>The data.</value>
public object Data
{
get; set;
}
/// <summary>
/// Gets or sets the errors.
/// </summary>
/// <value>The errors.</value>
public string[] Errors
{
get; set;
}
}
これは、プロパティ「.Success」、「.Data」、および「.Errors」を持つ JavaScript オブジェクトに変換されます。
したがって、検証コードが Errors 配列にすべての検証エラーを入力していた場合、ajax コールバック関数で簡単に
SUCCESS プロパティが "failure" に設定されているため、呼び出しの意図した目的が失敗したと判断します。
関連するすべてのエラー文字列を取得します。
アクションメソッドでこの種のパターンを使用すると、これを簡単に実行できます。
try
{
instance.Validate();
return Json(new AjaxResponse(myHtmlData));
}
catch(Exception ex)
{
var response = new AjaxResponse(ex);
// Get your validation errors here, put them into
// your ajax response's Errors property.
return Json(response);
}