Rik*_*iki 9 c# ajax jquery asp.net-mvc-5
我正试图在ajax调用后加载视图.在ajax调用之后,我的action方法将返回一个view在调用成功后将加载的方法.
AJAX我正在使用
function PostMethods(url,fname,lname,email){
Run Code Online (Sandbox Code Playgroud)var userRegisterViewModel = { FirstName: fname, LastName: lname, Email: email }; $.ajax({ type: 'Post', dataType: "json", url: url, contentType: 'application/json', data: JSON.stringify(userRegisterViewModel),//成功和错误代码
Run Code Online (Sandbox Code Playgroud)});}
我的ajax调用api方法,我正在通过fname,lname和email.现在我的api方法成功地将这些数据存储到数据库中它将返回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;
}
Run Code Online (Sandbox Code Playgroud)
在AXAJ和action方法中我应该写什么代码来做这件事
小智 13
AJAX调用保持在同一页面上,因此RedirectToAction不起作用.例如,您需要修改控制器以返回JSON
[HttpPost]
public JsonResult RegisterAndLogin(UserRegisterViewModel model)
{
bool successToStoreData = SomeMethod(model);
if (successToStoreData)
{
return null; // indicates success
}
else
{
return Json("Your error message");
}
}
Run Code Online (Sandbox Code Playgroud)
并修改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
}
}
})
Run Code Online (Sandbox Code Playgroud)