c# - 在 asp.net MVC 中调用 AJAX 后呈现 View

标签 c# jquery ajax asp.net-mvc-5

我正在尝试在 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 , lnameemail .现在我的 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/

相关文章:

c# - 嵌套的Json反序列化c#

javascript - AngularJS : date-time picker (vs) zoom in graph : one or the other not working

ajax - 是否可以在 JAWS 9 或 10 中强制刷新缓冲区?

javascript - div的动态高度

JQuery CSS - float 菜单栏

javascript - 拦截所有ajax调用?

asp.net-mvc - ASP.Net MVC TempData - 如何保持状态

c# - 如何使用 javascript 访问中继器内的 Div

c# - 使用 Unity 在 Oculus Rift 中重置/校准方向

c# - 在 C# .NET 中清理 ODBC DSN