Programing

"RedirectToAction"을 사용하여 컨트롤러에서 해시로 리디렉션

crosscheck 2020. 9. 25. 07:27
반응형

"RedirectToAction"을 사용하여 컨트롤러에서 해시로 리디렉션


안녕하세요 Mvc 컨트롤러에서 앵커를 반환하고 싶습니다.

컨트롤러 이름 = DefaultController;

public ActionResult MyAction(int id)
{
        return RedirectToAction("Index", "region")
}

색인으로 이동할 때 URL이

http://localhost/Default/#region

그래서

<a href=#region>the content should be focus here</a>

다음과 같이 할 수 있는지 묻지 않습니다. 내 URL에 앵커 태그를 추가하려면 어떻게해야합니까?


이 방법을 찾았습니다.

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

다음과 같은 자세한 방법을 사용할 수도 있습니다.

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


좋은 대답 gdoron. 여기에 내가 사용하는 다른 방법이 있습니다 (여기에서 사용 가능한 솔루션에 추가하기 위해).

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

분명히, gdoron의 대답으로 이것은이 간단한 경우에 다음과 같이 더 깨끗해질 수 있습니다.

return new RedirectResult(Url.Action("Index") + "#anchor_hash");

Squall의 대답을 확장하려면 문자열 보간을 사용하면 코드가 더 깔끔해집니다. 다른 컨트롤러의 작업에도 적용됩니다.

return Redirect($"{Url.RouteUrl(new { controller = "MyController", action = "Index" })}#anchor");

닷넷 코어의 간단한 방법

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

위의 결과는 / default / index # region 입니다. 세 번째 매개 변수는 # 뒤에 추가하는 조각 입니다.

Microsoft Docs-ControllerBase

참고 URL : https://stackoverflow.com/questions/10690466/redirect-to-a-hash-from-the-controller-using-redirecttoaction

반응형