在 .Net Core 应用程序中重定向

Redirect in .Net Core Application

我正在尝试对 .Net Core 进行一些操作,完成此操作后,我想将其重定向到 .cshtml 页面。在主页中,我有 table,在 table 中选择一行后,我将发送带有 ajax 的单元格的值。

AJAX

 $('#table').find('tr').click(function () {         
        var userName = $(this).find('td').text();
        $.ajax({
            url: "/Profile/printUser",
            type: 'POST',
            data: { "DisplayName": userName }
        });        
    });

看完这部分,我要去这个地区

函数

    [HttpPost]
    public IActionResult printUser(User user)
    {
        user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
        user.DisplayName = user.DisplayName.Trim(' ');
       
        User findUser = UserAdapter.GetUserByUserName(user.DisplayName);
      
        return RedirectToAction("ProfileScreen",findUser);      
    } 

我的操作完成了,我找到了我的用户。我想要做的就是在 cshtml 中打印此用户信息。但我无法将自己发送到页面。我怎样才能重定向自己?谢谢

索引

 public IActionResult ProfileScreen()
    {          
        return View();
    }

您无法从后端的 Ajax 调用重定向。使用 AJAX 的

  success: function(){ 
        windows.location.href = '/ProfileScreen'; 
    }

如果您想传回数据,return JSON 来自 MVC 操作,您的 JavaScript 将是:

$('#table').find('tr').click(function () {         
        var userName = $(this).find('td').text();
        $.ajax({
            url: "/Profile/printUser",
            type: 'POST',
            data: { "DisplayName": userName },
            success: function(data){
              window.location.href = '/ProfileScreen' + data.ID; //or whatever
            }
        });        
    });

解决方案

函数

[HttpPost]
        public JsonResult printUser(User user)
        {
            user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
            user.DisplayName = user.DisplayName.Trim(' ');
           
            User findUser = UserAdapter.GetUserByUserName(user.DisplayName);

            return Json(new { displayName = findUser.DisplayName});
        }