Home > Enterprise >  return view in action method with ajax
return view in action method with ajax

Time:01-24

I want to return a view in action (called Ajax) but it is possible that I will return Jason but if I return the view, it will not go to the view because the action was called with ajax.

action:

        [Route("/RecoveryPassword")]
        [HttpPost]
        public async Task<IActionResult> RecoveryPassword(string email)
        {
             var user=//something;
            if (user == null)
            {
                return Json(new { userNull =true});
            }

            if (user.IsActive == false)
            {
                return view("ViewName",ModelName));
            }

        }

ajax code:

                   $.ajax({
                       type: "Post",
                       dataType: "Json",
                       url: "/RecoveryPassword",
                       data: { "email": '[email protected]'},
                       success: function (result) {
                           if (result.userNull  == true) {
                              alert('hello');
                           }
                       },
                   });

What do you think I can do? Thankyou

CodePudding user response:

You can't render a view from AJAX. What you can do is use window.location.href= '@Url.Action(ViewName, controllerName)' or if you don't use AJAX then you can simply return View from your controller action.

CodePudding user response:

using ajax you can only return a partial view or a view as a partial

        [HttpPost("/RecoveryPassword")]
        public async Task<IActionResult> RecoveryPassword(string email)
        {
             var user=//something;
            if (user == null)
            {
                return Json(new { userNull =true});
            }

            if (user.IsActive == false)
            {
                return PartialView("ViewName",ModelName));
            }

        }

create a div in your view where you are going to put your returned view

<div id="partialView">
        <partial name=""ViewName" model="ModelName" />
</div>

and ajax

 success: function (result) {
            $("#partialView").html(result);
    },
  •  Tags:  
  • Related