ASP.NET MVC에서 이전 작업으로 리디렉션하려면 어떻게합니까?
페이지가 있다고 가정 해 봅시다.
some.web/articles/details/5
some.web/users/info/bob
some.web/foo/bar/7
일반적인 유틸리티 컨트롤러를 호출 할 수 있습니다.
locale/change/es
또는 authorization/login
어떻게 이러한 방법 (어떻게해야합니까 change
, login
) 이전의 행위로 리디렉션 ( details
, info
, bar
) 그들에게 이전 매개 변수를 전달하는 동안 ( 5
, bob
, 7
)?
한마디로 : 다른 컨트롤러에서 작업을 수행 한 후 방금 방문한 페이지로 리디렉션하는 방법은 무엇입니까?
시험:
public ActionResult MyNextAction()
{
return Redirect(Request.UrlReferrer.ToString());
}
대안으로, darin이 말한 것을 만져서 이것을 시도하십시오
public ActionResult MyFirstAction()
{
return RedirectToAction("MyNextAction",
new { r = Request.Url.ToString() });
}
그때:
public ActionResult MyNextAction()
{
return Redirect(Request.QueryString["r"]);
}
View의 버튼에서 리디렉션하려면 다음을 사용할 수 있습니다.
@Html.ActionLink("Back to previous page", null, null, null, new { href = Request.UrlReferrer})
단위 테스트에 관심이 없다면 간단히 다음과 같이 쓸 수 있습니다.
return Redirect(ControllerContext.HttpContext.Request.UrlReferrer.ToString());
이를 수행하는 방법에 대한 제안 :
- 반환 URL은 양식의 POST 요청과 유효성 검사에 실패한 경우에도 유지됩니다.
- 반환 URL은 초기 추천 URL에서 결정됩니다.
- TempData [] 또는 다른 서버 측 상태를 사용하지 않는 경우
- 기본 리디렉션을 제공하여 작업에 대한 직접 탐색을 처리합니다.
.
public ActionResult Create(string returnUrl)
{
// If no return url supplied, use referrer url.
// Protect against endless loop by checking for empty referrer.
if (String.IsNullOrEmpty(returnUrl)
&& Request.UrlReferrer != null
&& Request.UrlReferrer.ToString().Length > 0)
{
return RedirectToAction("Create",
new { returnUrl = Request.UrlReferrer.ToString() });
}
// Do stuff...
MyEntity entity = GetNewEntity();
return View(entity);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(MyEntity entity, string returnUrl)
{
try
{
// TODO: add create logic here
// If redirect supplied, then do it, otherwise use a default
if (!String.IsNullOrEmpty(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction("Index");
}
catch
{
return View(); // Reshow this view, with errors
}
}
다음과 같이 뷰 내에서 리디렉션을 사용할 수 있습니다.
<% if (!String.IsNullOrEmpty(Request.QueryString["returnUrl"])) %>
<% { %>
<a href="<%= Request.QueryString["returnUrl"] %>">Return</a>
<% } %>
javascript onclick을 사용하여 View Page의 일반 HTML 을 사용하는 Mvc
<input type="button" value="GO BACK" class="btn btn-primary"
onclick="location.href='@Request.UrlReferrer'" />
이것은 잘 작동합니다. 희망은 누군가를 돕는다.
@JuanPieterse는 이미 @Html.ActionLink
누군가가 댓글을 달거나 답변 할 수있는 경우@Url.Action
returnUrl 매개 변수 (URL 인코딩)를 변경 및 로그인 조치에 전달하고이 지정된 returnUrl로 내부 경로 재 지정하십시오. 로그인 동작은 다음과 같습니다.
public ActionResult Login(string returnUrl)
{
// Do something...
return Redirect(returnUrl);
}
.Net Core 2 MVC 사용하고 있으며 컨트롤러 사용에서 나에게 도움이되었습니다. HttpContext.Request.Headers["Referer"];
ViewBag.ReturnUrl
속성 을 사용하여 이전 페이지로 돌아갈 수 있습니다.
To dynamically construct the returnUrl in any View, try this:
@{
var formCollection =
new FormCollection
{
new FormCollection(Request.Form),
new FormCollection(Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
}
<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)
<!-- Option #2 -->
<a href="/Controller/Action/@object.ID?returnUrl=@Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>
<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>
This also works in Layout Pages, Partial Views and Html Helpers
Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)
참고URL : https://stackoverflow.com/questions/815229/how-do-i-redirect-to-the-previous-action-in-asp-net-mvc
'development' 카테고리의 다른 글
Eclipse 콘솔 크기 조정 (0) | 2020.07.20 |
---|---|
Rails에서 pluck과 collect의 차이점은 무엇입니까? (0) | 2020.07.20 |
Android 에뮬레이터 -5554 오프라인 (0) | 2020.07.20 |
부울에서 int로 변환 (0) | 2020.07.20 |
C # 정적 클래스 생성자 (0) | 2020.07.20 |