我正在尝试在 ajax 调用后加载 View 。在 ajax 调用之后,我的操作方法将返回一个 view
。调用成功后加载。
我正在使用 AJAX
function PostMethods(url, fname, lname, email) {
var userRegisterViewModel = { FirstName: fname, LastName: lname, Email: email }; $.ajax({ type: 'Post', dataType: "json", url: url, contentType: 'application/json', data: JSON.stringify(userRegisterViewModel),
//Success and error code
});}
我的 ajax 调用我传递的 api 方法 fname
, lname
和 email
.现在我的 api 方法成功地将这些数据存储到数据库中,它将返回 View
如果无法存储数据,它将返回一条错误消息,我可以在当前 View 中向用户显示该错误消息。在当前 View 的 HTML 中有一个空的 <spam>
显示错误信息。
我的操作方法是:
public ActionResult RegisterAndLogin(UserRegisterViewModel model)
{
ActionResult returnNextPage = null;
bool successToStoreData = SomeMethod(model);
if (successToStoreData)
{
returnNextPage = RedirectToAction(string.Empty, "Home");
}
else
{
//Text message to show to the user
}
return returnNextPage;
}
我应该在 AXAJ 和操作方法中编写什么代码来执行此操作
最佳答案
AJAX 调用停留在同一页面上,因此 RedirectToAction 不起作用。您需要修改您的 Controller 以返回 JSON,例如
[HttpPost]
public JsonResult RegisterAndLogin(UserRegisterViewModel model)
{
bool successToStoreData = SomeMethod(model);
if (successToStoreData)
{
return null; // indicates success
}
else
{
return Json("Your error message");
}
}
并修改AJAX函数
$.ajax({
type: 'Post',
dataType: "json",
url: url,
contentType: 'application/json',
data: JSON.stringify(userRegisterViewModel),
success: function(message) {
if (message) {
$('yourSpanSelector').text(message); // display the error message in the span tag
} else {
window.location.href='/YourController/YourAction' // redirect to another page
}
}
})
关于c# - 在 asp.net MVC 中调用 AJAX 后呈现 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25994897/