Redirect to a hash from the controller using “RedirectToAction”

前端 未结 4 1281
不知归路
不知归路 2020-11-29 22:41

Hello I want to return an anchor from Mvc Controller

Controller name= DefaultController;

public ActionResult MyAction(int id)
{
        return Redi         


        
相关标签:
4条回答
  • 2020-11-29 23:14

    Great answer gdoron. Here's another way that I use (just to add to the available solutions here).

    return Redirect(String.Format("{0}#{1}", Url.RouteUrl(new { controller = "MyController", action = "Index" }), "anchor_hash");
    

    Obviously, with gdoron's answer this could be made a cleaner with the following in this simple case;

    return new RedirectResult(Url.Action("Index") + "#anchor_hash");
    
    0 讨论(0)
  • 2020-11-29 23:14

    A simple way in dot net core

    public IActionResult MyAction(int id)
    {
        return RedirectToAction("Index", "default", "region");
    }
    

    The above yields /default/index#region. The 3rd parameter is fragment which it adds after a #.

    Microsoft docs - ControllerBase

    0 讨论(0)
  • 2020-11-29 23:26

    To Expand on Squall's answer: Using string interpolation makes for cleaner code. It also works for actions on different controllers.

    return Redirect($"{Url.RouteUrl(new { controller = "MyController", action = "Index" })}#anchor");
    
    0 讨论(0)
  • 2020-11-29 23:35

    I found this way:

    public ActionResult MyAction(int id)
    {
        return new RedirectResult(Url.Action("Index") + "#region");
    }
    

    You can also use this verbose way:

    var url = UrlHelper.GenerateUrl(
        null,
        "Index",
        "DefaultController",
        null,
        null,
        "region",
        null,
        null,
        Url.RequestContext,
        false
    );
    return Redirect(url);
    

    http://msdn.microsoft.com/en-us/library/ee703653.aspx

    0 讨论(0)
提交回复
热议问题