![](/img/trans.png)
[英]How to render a view into another one, after an ajax request in C# and ASP.NET MVC?
[英]Render a View after an AJAX call in asp.net MVC
我正试图在ajax调用后加载视图。 在ajax调用之后,我的action方法将返回一个view
,该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),
//成功和错误代码
});}
我的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;
}
在AXAJ和action方法中我应该写什么代码来做这件事
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");
}
}
并修改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
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.