Search code examples
asp.net-corerazor-pages

Add fragment to RedirectToPage


How to redirect to a page passing a fragment?

I'm unable to add fragment to RedirectToPage action. If I add "#" as part of string, it will be converted in %23 and therefore unuseful

PostAction

public async Task<IActionResult> OnPostAsync()
{
   if (!ModelState.IsValid) { return Page(); }

   _context.Attach(AnagraficaClientiContatti).State = EntityState.Modified;

   try{
       await _context.SaveChangesAsync();
   } 
   catch (DbUpdateConcurrencyException)
   {
     if (!AnagraficaClientiContattiExists(
                 AnagraficaClientiContatti.AnagraficaClientiContattiID))
     {
        return NotFound();
     }
     else
     {
       throw;
      }
   }

   return RedirectToPage(
            "../Index", 
            new { id = Request.Query["idmaster"], 
                  pgm = Request.Query["pgm"], 
                  pgs1 = Request.Query["pgs1"], 
                  activetab = Request.Query["activetab"], 
                  searchstring = Request.Query["searchstring"] }
   );
}

and this work fine, but i need to redirect to above page with "#specificsection" at the end.

I tried to change the call to

return RedirectToPage(
        "../Index", 
        new { id = Request.Query["idmaster"], 
              pgm = Request.Query["pgm"], 
              pgs1 = Request.Query["pgs1"], 
              activetab = Request.Query["activetab"], 
              searchstring = Request.Query["searchstring"] 
                             + "#specificsection" }
);

but browser return a "wrong" url with %23 instead #

?id=20&pgm=2&pgs1=2&activetab=custom-tabs-one-contatti&searchstring=text%23specificsection

No luck, passing fragment as third or fourth parameter (with third null ) in RedirectToPage, as i understood from documentation.

Can someone help me to understand what i'm doing wrong?

Thanks in advance.

Best

Massimo


Solution

  • Use the overload that takes a string?, string?, object?, string? for the page, page handler (which is null), route values and a fragment :

    return RedirectToPage(
               pageName: "/Index", 
               pageHandler: null, 
               routeValues: new { 
                             id = Request.Query["idmaster"], 
                             pgm = Request.Query["pgm"], 
                             pgs1 = Request.Query["pgs1"],
                             activetab = Request.Query["activetab"], 
                             searchstring = Request.Query["searchstring"]},
               fragment: "specificsection")
    );
    

    From the docs for RedirectToPage(String, String, Object, String)

    Parameters

    • string pageName // name of the page.
    • string pageHandler // page handler to redirect to.
    • Object routeValues // parameters for a route.
    • string fragment // fragment to add to the URL.