Redirect in .Net Core Application

2.7k views Asked by At

im trying to do some operation .Net Core and after this operation is done, i want to redirect it to a .cshtml page. In homepage i have table, after selecting a row in the table, im sending the value of the cell with ajax.

Table

AJAX

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

After this part, im going to this area

FUNCTION

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

My operations are finished, i found my user. All i want to do is print this users information in cshtml. But i cant send myselft to the page. How can i redirect myself? Thanks.

INDEX

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

There are 2 answers

7
bobek On BEST ANSWER

You can't redirect from Ajax call in the backend. Use AJAX's

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

If you want to pass data back, return JSON from MVC action and your JavaScript would be:

$('#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
            }
        });        
    });
0
Berkin On

SOLUTION

FUNCTION

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