Emilio Largo
Emilio Largo

Reputation: 3

How to avoid long and complex URL when using RedirectToPage?

I am using a controller to return data to a Razor Page. I am returning employee information:

public IActionResult View(int id)
    {
        var employee = _context.Employees.Where(i => i.Id == id).Select(i => new {
            i.FirstName,
            i.LastName,
            i.PhoneNumber,
            i.Email
        });
        string employee = JsonConvert.SerializeObject(employee);
        return RedirectToPage("/Employees/View", new { empId = id, emp = employee });
    }

I use the Razor Page's model's OnGet() to get First Name, etc., manipulate them, then display accordingly on the page. This is fine really, except that all that information is visible in the URL. This is a small part of what the page is doing, and I needed to use Page instead of a View. Can you let me know how I can pass the employee info to the page without showing it in the URL?

Upvotes: 0

Views: 93

Answers (1)

Rena
Rena

Reputation: 36685

I think you could use TempData:

public IActionResult View(int id)
{
    var employee = _context.Employees.Where(i => i.Id == id).Select(i => new {
        i.FirstName,
        i.LastName,
        i.PhoneNumber,
        i.Email
    });
    string employee = JsonConvert.SerializeObject(employee);
    
    //add the following code....
    TempData["empId "] = id;
    TempData["employee"] = employee;

    return RedirectToPage("/Employees/View");
}

In your /Employees/View method:

public IActionResult View()
{
    var emp = TempData["employee"] as string;
    var empId = TempData["empId "];
    return Page();
}

Reference:

https://stackoverflow.com/a/63461336/11398810

Upvotes: 1

Related Questions