您需要返回多条信息以供回复。幸运的是,你可以使用 JSON 轻松地做到这一点,如果你告诉它响应类型是 json,jQuery 会自动为你处理它。您进入 ajax 回调函数的对象将包含您需要的所有数据作为不同的属性。
我建议养成在每次 ajax 调用时返回“成功”或“失败”状态代码的习惯,以及一系列错误。 有关我的意思的更多信息,请参阅这篇很棒的博客文章。
原因是 ajax 调用从根本上总是“成功”,除非服务器实际上无法处理请求并返回失败的 http 状态代码。如果请求的结果类似于验证错误,但服务器仍然返回某种文本响应,那么即使应用程序操作失败,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 属性设置为“失败”。
获取所有相关的错误字符串。
您可以在您的操作方法中使用这种模式轻松地做到这一点:
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);
}