我使用Visual Studio 2010在我的本地计算机上开发了一些Web应用程序已有几天了.昨晚我在IIS 7上部署了我的应用程序,并且令人沮丧地偶然发现了一个主要的节目限制器.该问题与Ajax请求中的错误处理有关.首先,我有一些编辑屏幕可以处理ajax请求.以下是Ajax编辑屏幕的ajax部分.
@using (Ajax.BeginForm("_CityEdit", null, new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "content",
LoadingElementId="imgSaveLoading", OnFailure="onError",
OnSuccess = "onSuccess" }, new { id = "frmCity" })) {
<img id="imgSaveLoading" alt="loading" src="@Url.Content("~/Content/Telerik/Vista/loading.gif")" class="ajax-loader-user" />
<div class="content" id="content">
@{Html.RenderPartial("_CityEdit");}
</div>
<!-- Some Other code here -->
}
Run Code Online (Sandbox Code Playgroud)
我依赖于上面的Ajax.BeginForm()的"onError"回调.所以在我的控制器中,每当我想向用户显示错误(模型错误或任何其他错误)时,我只是乐观地将服务器响应设置为500(内部服务器错误),希望这会导致Ajax.BeginForm的"OnError"处理程序()被调用.这是我在控制器中如何做到这一点的片段.
[HttpPost]
public ActionResult _CityEdit(CityViewModel viewModel) {
city = cityManager.FindCity(viewModel.City.Id, false);
// Validate Model here
if (!TryUpdateModel(city, "City")) {
Response.StatusCode = 500;
return PartialView("_CityEdit", viewModel);
}
Run Code Online (Sandbox Code Playgroud)
从上面的代码可以看出,我返回了PartialView,如果它包含Model Errors,它们将自动显示在Ajax Edit屏幕上.然后在"OnError"JavaScript中,我只需用控制器返回的PartialView替换相关的div,就像这样.
function onError(xhr) {
$('#content').html(xhr.responseText); …Run Code Online (Sandbox Code Playgroud)