How do I add a parameter for an anchor/hash to a RedirectToRouteResult?
I want to use a RedirectToRouteResult to redirect to a url like /users/4#Summary. Using ASP.NET MVC 1.0, I haven't been able to find a w开发者_开发技巧ay to do that - have I missed it?
You should properly build your routes in route table. Eg.:
routes.MapRoute("MyRoute" ,"{controler}/{id}#{detail}" ,new { controller = "users", action = "index", id = (string)null, detail = "Summary" });
UrlHelper.GenerateUrl includes a fragment parameter. I created an extension method
public static string Action(this UrlHelper url, string actionName, string controllerName, string fragment, object routeValues)
{
return UrlHelper.GenerateUrl(
routeName: null,
actionName: actionName,
controllerName: controllerName,
routeValues: new System.Web.Routing.RouteValueDictionary(routeValues),
fragment: fragment,
protocol: null,
hostName: null,
routeCollection: url.RouteCollection,
requestContext: url.RequestContext,
includeImplicitMvcValues: true /*helps fill in the nulls above*/
);
}
Then I created a RedirectToFragmentResult class
public class RedirectToFragmentResult: RedirectResult
{
public UrlHelper Url {get;set;}
public string Action { get; set; }
public string Controller { get; set; }
public string Fragment { get; set; }
public object RouteValues { get; set; }
public RedirectToFragmentResult(UrlHelper url, string action, string controller, string fragment, object routeValues)
:base(url.Action(action, controller, fragment, routeValues))
{
Url = url;
Action = action;
Controller = controller;
Fragment = fragment;
RouteValues = routeValues;
}
}
Then you can just create a new RouteValueDictionary(result.RouteValues) in your unit test to check it the way you would with a RedirectToRouteResult.
I had a similar problem, take a look here:
Linking to location on page (#id) through ASP.NET MVC mechanisms?
I ended up creating a route using #.
I do a something like that on my site here. But it's not with RedirectToRouteResult
. RedirectToRouteResult
does not support including an anchor part to the url.
You need to build the link yourself and perhaps even the logic to handle the processing of the anchor part - as i did. My application tries to replicate functionality similar to that of the Facebook photo gallery views. Each link to a different page must have a unique url, so for this i use the anchor part. But coz it does not translate direct to a route i have to parse the anchor part of the url manually on the page and use ajax to load in the appropriate content. This is what i wanted so it works for me.
Download the source code of MVC and check out how RedirectToRouteResult works
There may be better ways but a simple inheritance of RedirectToRouteResult and an override of ExecuteResult to allow an optional anchor part should fix the problem
精彩评论