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

后端 未结 4 1212
我在风中等你
我在风中等你 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 11:11

    You can get the current URL via

    string controller = (string)ViewContext.RouteData.Values["controller"];
    string action = (string)ViewContext.RouteData.Values["action"];
    string url = Url.Action(action, controller);
    

    You can do this in an HtmlHelper or in the controller that renders the login view.

    Store url in a hidden field as you did, then in your post action:

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

    The benefit of using Url.Action is that it will use your route table to generate the URL, meaning if your routes ever change, you won't have to change this code.

提交回复
热议问题