In .NET MVC, is there an easy way to check if I'm on the home page?

后端 未结 4 1134
我在风中等你
我在风中等你 2021-02-14 10:25

I need to take a particular action if a user logs in from the home page. In my LogOnModel, I have a hidden field:

@Html.Hidden(\"returnUrl\", Request.Url.Absolut         


        
4条回答
  •  误落风尘
    2021-02-14 10:54

    One way to approach this would be to look for the specific controller in the RouteData. Assuming that the controller you are using for the home page is called "HomeController", then the RouteData for the request would contain the value "Home" for the key "Controller".

    It would look something like this:

    instead of (or in addition to if you have other reasons for it):

     @Html.Hidden("returnUrl", Request.Url.AbsoluteUri)
    

    you would have:

     @Html.Hidden("referrer", Request.RequestContext.RouteData.Values['Controller'])
    

    and your controller would look like:

    [HttpPost]
    public ActionResult LogOnInt(LogOnModel model)
    {
       if (model.referrer = "Home")
       {
          return Json(new { redirectToUrl = @Url.Action("Index","Home")});
       }
     }
    

    This would eliminate the need for using .Contains()

    Update:

    You could also eliminate the need for a hidden field (and thereby reduce overall page-weight for what would seem like every page in your application) by mapping the referrer url (Request.UrlReferrer.AbsoluteUri) to a route. There is a post about that here.

    How to get RouteData by URL?

    The idea would be to use the mvc engine to map a referrer url to an MVC route in the LogOnInt method, allowing the code to be entirely self contained.

    This would probably be cleaner than putting the controller name and action name out there for the world to see along with scripting to push it back to the server.

提交回复
热议问题