我已經實現了一個控制器來創建新用戶。當它成功創建用戶時,它將重定向到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");
}
形式提交被攔截使用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;
});
當錯誤發生時它工作正常,但我不知道如何實施成功案例。
我向其他選擇開放。
我有類似的情況。我有包含填寫表單的頁面。頁面上的按鈕從一個字段中提取數據,調用Web服務查找相關數據,如果查找成功,則重定向到另一個頁面。我使用Ajax來繞過數據驗證,因爲驗證字段不適用於按鈕的查找操作。如果查找失敗,我想在同一頁面上顯示一個錯誤。至少這是我想要做的。 – Suncat2000 2011-09-09 16:46:00