Asp.net mvc - How to return a user to a previous action?

Imagine a scenario when I have a subformat on a page. This sub-format is contained in partial user control and is placed in its own dedicated controller action. In case of violation of the business rule, I want to return the same view that was previously previously.

Example:

  • The user is in / example / page 1, which displays a partial "SignOnForm"
  • Signs of the SignOn form for "Accounts / SignOn".
  • If something is invalid, I want to return the user to / example / page 1 with the model state in time. However, I cannot hardcode the view because the user may be on another page, such as / othercontroller / page 10.
+3
source share
2 answers

You can use the returned URL completely through the SignOn process using the query string of the request.

First, indicate the page you want to return to whenever you produce a partial SignOn sign:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%@ Import Namespace="Microsoft.Web.Mvc"%>

<!-- Your Example/Page1 page -->

<% if (!User.IsAuthenticated) %>
    <%= Html.RenderAction("SignOn", "Account", new { returnUrl = Request.Url.PathAndQuery }); %>

Use RenderAction if the current context is not an Account Controller. This feature is currently not available in the MVC release, so you need to include the ASP.NET MVC Future library in your solution.

Next, the SignOn controller:

public ActionResult SignOn(string returnUrl)
{
    if (User.Identity.IsAuthenticated)
    {
        User user = userRepository.GetItem(u => u.aspnet_UserName == User.Identity.Name);
        return !string.IsNullOrEmpty(returnUrl)
               ? Redirect(returnUrl)
               : (ActionResult) RedirectToAction("Index", "Home");
    }
    return PartialView();
}

SignOn Form:

 <% using (Html.BeginForm("SignOn", "Account", new { returnUrl = Request.QueryString["returnUrl"] },FormMethod.Post,new {@class="my_signOn_class"}))
    { %>
         <!-- Form -->
 <% } %>

Finally, in the SignOn controller that processes the POST form, you can return the user to "returnURL" using the following code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SignOn(FormCollection formCollection, string returnUrl)
{
    if (BusinessRuleViolated(formCollection))
    {
        if(!string.IsNullOrEmpty(returnUrl))
        {
            return Redirect(returnUrl);
        }
        return RedirectToAction("Index", "Home");
    }

    // SignIn(...)
}
+2
source
public SignOn(string username, string password)
{
  //login logic here
  ...

  //Now check if the user is authenticated.
  if(User.IsAuthenticated)
  {
    //Redirect to the next page
    return RedirectToAction("page10", "Other");
  }
  else
  {
    // You could also pass things such as a message indicating the user was not authenticated.
    return RedirectToAction("page1", "Example");
  }
}

, "" "", . , , .

0

Source: https://habr.com/ru/post/1716715/


All Articles