Display view after AJAX call in asp.net MVC

I am trying to load a view after ajax call. After calling ajax, my action method will return a view that will be loaded after the call completes successfully.

AJAX I use

PostMethods function (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), 

// Code of success and error

 });} 

My ajax calls the api method, where I go through fname , lname and email . Now my api method successfully saves this data in the database, it will return view , if it cannot save the data, it will return an error message that I can show the user in the current view. There is an empty <spam> in the HTML of the current view to display an error message.

My action method:

  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 should I write for this in AXAJ and the action method

+6
source share
1 answer

AJAX calls remain on the same page, so RedirectToAction does not work. You need to change 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 change the function of 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 } } }) 
+8
source

Source: https://habr.com/ru/post/975713/


All Articles