In ASP.NET MVC, how does response.redirect work?

后端 未结 5 1271
长情又很酷
长情又很酷 2020-12-13 13:49

I have used response.redirect in classic ASP and ASP.NET webforms. However, with MVC 2.0, I am running into something peculiar.

I have a private method in a contr

相关标签:
5条回答
  • 2020-12-13 14:26

    In ASP.NET MVC, you would normally redirect to another page by returning a RedirectResult from the controller method.

    Example:

    public ActionResult Details(int id)
    {
         // Attempt to get record from database
         var details = dataContext.GetDetails(id);
    
         // Does requested record exist?
         if (details == null)
         {
             // Does not exist - display index so user can choose
             return RedirectToAction("Index");
         }
    
         // Display details as usual
         return View(details);
    }
    
    0 讨论(0)
  • 2020-12-13 14:28

    The conventional mechanism to redirect in ASP.Net MVC is to return an object of type RedirectResult to the client. If this is done before your View method is called, your view methods will never be called.

    If you call Response.Redirect yourself, instead of letting Asp.Net MVC's front controller do that for you, your controller method will continue on until it finishes or throws an exception.

    The idiomatic solution for your problem is to have your private method return a result that your controller can use.

    for example:

    public ActionResult Edit(MyEntity entity)
    {
      if (!IsValid()) return Redirect("/oops/");
      ...
      return View();
    
    }
    
    private bool IsValid()
    {
      if (nozzle==NozzleState.Closed) return false;
      if (!hoseAttached) return false;
      return (userRole==Role.Gardener);
    }
    
    0 讨论(0)
  • 2020-12-13 14:38

    its recommended and its the only way to redirect to asp.net form in mvc controller action by using

    return Redirect("/page/pagename.aspx");
    

    other way we can redirect by using ( not recommended and bad way )

    Response.Redirect("/page/pagename.aspx", true);
    

    it will work for redirect, but problem is it will clear all of our Session values. so why its not recommended.

    0 讨论(0)
  • 2020-12-13 14:38

    try this code in mvc view page lode

            if (Session["UserName"] == null)
            {
                this.Response.Redirect("LogOn");
    
            }
    
    0 讨论(0)
  • 2020-12-13 14:39

    In MVC never use Response.Redirect use

    return RedirectToAction("ActionResultName", "ControllerName");
    

    As to WHY to NOT use Response.Redirect in MVC:

    1. Performance issues with it
    2. Not following standard asp.net MVC pattern and conventions that have been built specifically FOR MVC.
    0 讨论(0)
提交回复
热议问题