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

后端 未结 1 971
渐次进展
渐次进展 2021-02-08 02:56

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.

<
1条回答
  •  爱一瞬间的悲伤
    2021-02-08 03:17

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

    and modify the AJAX function

    $.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
        }
      }
    })
    

    0 讨论(0)
提交回复
热议问题