“/”应用程序中的服务器错误。无法找到该资源。 HTTP 404,请求的 URL:/UsersPage/undefined

问题描述 投票:0回答:1

描述:HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请检查以下 URL 并确保拼写正确。

请求的 URL:/UsersPage/undefined

我有这个ajax脚本,我应该将用户重定向到指定的url:

$.ajax({
    url: '@Url.Action("UsersHome", "UsersPage")',
    type: 'POST',
    data: {
            chosenMood: chosenMood    
          },
    success: function(response) {
            // Handle the success response
            console.log('Success:', response);
            // Redirect to the received URL
            window.location.href = response.redirectUrl;
    },
    error: function(xhr, status, error) {
            // Handle errors, if any
            console.error('Error:', error);
            // Optionally, you can display an error message to the user
            alert('An error occurred. Please try again later.');
    }
    });

这是控制器或目标页面:

public ActionResult UsersHome()    
{
    if (User.Identity.IsAuthenticated)
    {
        //Session["ChosenMood"] = chosenMood;
        var redirectUrl = Url.Action("UsersHome", "UsersPage");
        //return Json(new { redirectUrl }, JsonRequestBehavior.AllowGet);
        return View();
    } else
    {
        return RedirectToAction("../Home/Index");
    }
}
javascript c# ajax asp.net-mvc asp.net-ajax
1个回答
0
投票

这段代码有一些问题。

  1. 如果您在控制器中向操作方法发出 ajax 请求,如果它返回视图,您将在 ajax 响应中获得 html 代码。因此,在您的情况下,您需要发送带有重定向 URL 的 Json

  2. 此外,在您的json中发送redirectUrl之后,它会抛出404,因为成功函数window.location.href将调用GET操作方法Url.Action(“UsersHome”,“UsersPage”),这实际上是您控制器中的POST(假设).

像这样修改你的代码将会起作用

控制器代码

[HttpGet]
    public ActionResult UsersHome()
    {
        bool auth = true;
        var isAjax = Request.IsAjaxRequest();
        if (auth)
        {
            //Session["ChosenMood"] = chosenMood;
            var redirectUrl = Url.Action("UsersHome", "UsersPage");
            if(isAjax)
                return Json(new { redirectUrl=redirectUrl }, JsonRequestBehavior.AllowGet);

            return View();
        }
        else
        {
                return Json(new { redirectUrl= "../Home/Index" });
        }
    }

Ajax 代码

 $.ajax({
url: '@Url.Action("UsersHome", "UsersPage")',
type: 'GET',
        data: {
            chosenMood: "chosenMood"
        },
success: function(response) {
        // Handle the success response
        console.log('Success:', response);
        // Redirect to the received URL
        window.location.href = response.redirectUrl;
},
error: function(xhr, status, error) {
        // Handle errors, if any
        console.error('Error:', error);
        // Optionally, you can display an error message to the user
        alert('An error occurred. Please try again later.');
}
});

注意 Request.IsAjaxRequest() 将检查 ajax 请求,并且第一次它将返回 Json 。在 window.location.href 上它将渲染视图。

© www.soinside.com 2019 - 2024. All rights reserved.