简体   繁体   English

在asp.net MVC中进行AJAX调用后渲染视图

[英]Render a View after an AJAX call in asp.net MVC

I'm trying to load a view after an ajax call. 我正试图在ajax调用后加载视图。 After the ajax call my action method will return a view which is going to be loaded after the call is success. 在ajax调用之后,我的action方法将返回一个view ,该view将在调用成功后加载。

AJAX I'm using AJAX我正在使用

function PostMethods(url, fname, lname, email) { 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 //成功和错误代码

 });} 

My ajax calling an api method where I'm passing fname , lname and email . 我的ajax调用api方法,我传递的是fnamelnameemail 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. 现在我的api方法成功地将这些数据存储到数据库中它将返回一个View如果无法存储数据,它将返回一条错误消息,我可以在当前视图中向用户显示该消息。 In the HTML of the current view has an empty <spam> to show the error message. 在当前视图的HTML中有一个空<spam>来显示错误消息。

My Action Method is: 我的行动方法是:

    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;
    }

What code I should write to do this in AXAJ and action method 在AXAJ和action方法中我应该写什么代码来做这件事

AJAX calls stay on the same page so RedirectToAction does not work. AJAX调用保持在同一页面上,因此RedirectToAction不起作用。 You need to modify your controller to return JSON, for example 例如,您需要修改控制器以返回JSON

[HttpPost]
public JsonResult RegisterAndLogin(UserRegisterViewModel model)
{
  bool successToStoreData = SomeMethod(model);
  if (successToStoreData)
  {
    return null; // indicates success
  }
  else
  {
    return Json("Your error message");
  }
}

and modify the AJAX function 并修改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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM