Dan*_*lba 10 ajax asp.net-mvc jquery asp.net-mvc-2
我已经实现了一个控制器来创建新用户.当它成功创建用户时,它会重定向到Index().
我想要的是在一切正常时重定向,但留在当前页面并在出现故障时看到错误.
我使用的是jQuery ajax带MVC.
我的控制器看起来像这样:
[Authorize]
public ActionResult CreateUser(string username)
{
try
{
//here the logic to create the user
}
catch (Exception ex)
{
string error = string.Format("Error creating user: {0}", ex.Message);
Response.StatusCode = 500;
Response.Write(error);
}
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
使用jQuery拦截表单提交,然后使用ajax进行调用:
$("#new-user-form").submit(function() {
var form = $(this);
$.ajax({
type: "GET",
url: form.attr('action'),
data: form.serialize(),
success: function(data, textStatus, xhr) {
//At this point I would like to redirect
},
error: function(xhr, textStatus, errorThrown) {
$(".error-summary").html(xhr.responseText);
}
});
//cancel the event
return false;
});
Run Code Online (Sandbox Code Playgroud)
发生错误时它可以正常工作,但我不知道如何实现成功案例.
我对其他选择开放了.
Dar*_*rov 29
如果您要在成功动作中重定向,为什么使用AJAX?AJAX的目的是仅刷新站点的一部分而不重新加载整个页面.如果在成功动作中你将重定向,那将完全击败你从AJAX获得的所有目的和好处.但是因为你问这里你能做什么:
[Authorize]
public ActionResult CreateUser(string username)
{
...
if (Request.IsAjaxRequest())
{
return Json(new { redirectToUrl = Url.Action("Index") });
}
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)
然后:
success: function(data, textStatus, xhr) {
window.location.href = data.redirectToUrl;
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23864 次 |
| 最近记录: |