在asp.net MVC中进行AJAX调用后呈现视图 [英] Render a View after an AJAX call in asp.net MVC
问题描述
我正在尝试在ajax调用后加载视图.在ajax调用之后,我的操作方法将返回view
,调用成功后将加载该view
.
I'm trying to load a view after an ajax call. After the ajax call my action method will return a view
which is going to be loaded after the call is success.
我正在使用的AJAX
AJAX I'm using
函数PostMethods(网址,fname,lname,电子邮件){
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),
//成功和错误代码
});}
我的ajax调用api方法,并在其中传递fname
,lname
和email
.现在,我的api方法已成功将那些数据存储到数据库,如果无法存储数据,它将返回View
,它将返回一条错误消息,我可以在当前视图中向用户显示该消息.在当前视图的HTML中,有一个空的<spam>
来显示错误消息.
My ajax calling an api method where I'm passing fname
, lname
and email
. Now my api method successfully stores those data to database it will return a View
if fails to store data it will return an error message which I can show to user in current view. In the HTML of the current view has an empty <spam>
to show the error message.
我的操作方法是:
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和操作方法中编写什么代码
What code I should write to do this in AXAJ and action method
推荐答案
AJAX调用保持在同一页面上,因此RedirectToAction不起作用.您需要修改控制器以返回JSON,例如
AJAX calls stay on the same page so RedirectToAction does not work. You need to modify your controller to return JSON, for example
[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
}
}
})
这篇关于在asp.net MVC中进行AJAX调用后呈现视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!