Hai*_*ter 8 c# asp.net-mvc razor
如果用户从主页登录,我需要采取特定操作.在我的LogOnModel中,我有一个隐藏字段:
@Html.Hidden("returnUrl", Request.Url.AbsoluteUri)
Run Code Online (Sandbox Code Playgroud)
在我的Controller中,我需要检查该值是否为主页.在下面的示例中,我正在检查用户是否在特定页面上("Account/ResetPassword").有没有办法检查它们是否在主页上而不诉诸正则表达式?
[HttpPost]
public ActionResult LogOnInt(LogOnModel model)
{
if (model.returnUrl.Contains("/Account/ResetPassword"))
{
return Json(new { redirectToUrl = @Url.Action("Index","Home")});
}
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?一百万谢谢!
小智 7
解决这个问题的一种方法是在中寻找特定的控制器RouteData.假设您用于主页的控制器称为"HomeController",则RouteData请求将包含键"Controller"的值"Home".
它看起来像这样:
而不是(或除了你有其他原因):
@Html.Hidden("returnUrl", Request.Url.AbsoluteUri)
Run Code Online (Sandbox Code Playgroud)
你将会拥有:
@Html.Hidden("referrer", Request.RequestContext.RouteData.Values['Controller'])
Run Code Online (Sandbox Code Playgroud)
你的控制器看起来像:
[HttpPost]
public ActionResult LogOnInt(LogOnModel model)
{
if (model.referrer = "Home")
{
return Json(new { redirectToUrl = @Url.Action("Index","Home")});
}
}
Run Code Online (Sandbox Code Playgroud)
这将消除使用的需要 .Contains()
更新:
您还可以通过将引用URL url(Request.UrlReferrer.AbsoluteUri)映射到路由来消除对隐藏字段的需求(从而减少应用程序中每个页面的整体页面权重).这里有一篇关于此的帖子.
我们的想法是使用mvc引擎将引用者URL映射到方法中的MVC路由LogOnInt,从而允许代码完全自包含.
这可能比把控制器名称和操作名称放在那里更干净,让全世界都可以看到脚本将其推回服务器.
您可以通过以下方式获取当前 URL
string controller = (string)ViewContext.RouteData.Values["controller"];
string action = (string)ViewContext.RouteData.Values["action"];
string url = Url.Action(action, controller);
Run Code Online (Sandbox Code Playgroud)
您可以在 HtmlHelper 或呈现登录视图的控制器中执行此操作。
像您一样存储url在隐藏字段中,然后在您的后期操作中:
[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")});
}
}
Run Code Online (Sandbox Code Playgroud)
使用的好处Url.Action是它将使用您的路由表来生成 URL,这意味着如果您的路由发生变化,您无需更改此代码。
在任何视图中,以下代码返回当前控制器名称.
@ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString()
Run Code Online (Sandbox Code Playgroud)
这很容易吗?:)
| 归档时间: |
|
| 查看次数: |
14193 次 |
| 最近记录: |