Riki Riki - 7 months ago 32
Javascript Question

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

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 I'm using



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
. 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.

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

Answer

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