Seb*_*eth 1 mvccontrib asp.net-mvc-3
我正在使用MvcContrib的强类型RedirectToAction()从一个控制器动作重定向到另一个,同时避免我的应用程序流中的魔术字符串,如下所示:
this.RedirectToAction<FooController>(c => c.Bar());
Run Code Online (Sandbox Code Playgroud)
然后重定向到
/foo/bar/
Run Code Online (Sandbox Code Playgroud)
...但是现在我希望能够在末尾重定向到带有anchor/hashtag的URL,并将窗口滚动到<a name="yarrr" />标记,如下所示:
/foo/bar/#yarrr
Run Code Online (Sandbox Code Playgroud)
我可以将标签放在TempData []中,将其写入javascript变量并通过javascript滚动窗口 - 但我宁愿遵循惯例并将主题标签作为我的URL的结尾.
任何想法或自制的解决方案?MvcContrib似乎不支持它.
我不知道在MvcContrib中存在这样的ActionLink重载,但写一个会很简单:
using System;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
public static class HtmlExtensions
{
public static IHtmlString ActionLink<TController>(
this HtmlHelper html,
Expression<Action<TController>> action,
string linkText,
object htmlAttributes,
string fragment
) where TController : Controller
{
var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper
.GetRouteValuesFromExpression(action);
return html.RouteLink(
linkText: linkText,
routeName: null,
protocol: null,
hostName: null,
fragment: fragment,
routeValues: routeValues,
htmlAttributes: new RouteValueDictionary(htmlAttributes)
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你看来:
@(Html.ActionLink<FooController>(c => c.Bar(), "click me", null, "yarrr"))
Run Code Online (Sandbox Code Playgroud)
更新:
显然我误解了你的问题,因为你RedirectToAction在控制器中寻找一个方法,而不是在视图中.我的答案和以前一样:I am not aware of the existence of such an RedirectToAction overload in MvcContrib but writing one would be trivial:
using System;
using System.Linq.Expressions;
using System.Web.Mvc;
public static class HtmlExtensions
{
public static RedirectResult RedirectToAction<TController>(
this Controller controller,
Expression<Action<TController>> action,
string fragment
) where TController : Controller
{
var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper
.GetRouteValuesFromExpression(action);
var urlHelper = new UrlHelper(controller.ControllerContext.RequestContext);
return new RedirectResult(
UrlHelper.GenerateUrl(
routeName: null,
actionName: null,
controllerName: null,
protocol: null,
hostName: null,
fragment: fragment,
routeValues: routeValues,
routeCollection: urlHelper.RouteCollection,
requestContext: controller.ControllerContext.RequestContext,
includeImplicitMvcValues: true
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器内:
public class HomeController : Controller
{
public ActionResult Index()
{
return this.RedirectToAction<FooController>(c => c.Bar(), "yarrr");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1434 次 |
| 最近记录: |