Linking to location on page (#id) through ASP.NET MVC mechanisms?
My example:
I have a View
that presents a set of div tags that has content populated from the datamodel.
[Multiple of these, with different location_id, naturally]
&开发者_C百科lt;div>
<a name="location_id"></a>
Content
</div>
Now, I have a form [in its own view] that submits content that adds another record to the datamodel. Once the record is create and submitted, I redirect back to the Action
that returns the View
with the <div>
listing.
My challenge:
I'd like the page to focus the <div>
block that was just created. Ideally I'd like to do this without the use of javascript, - I'd like to use an #location_id ending to the URL.
Like so: http://site/Controller/Action/Id#12
(or something along those lines).
Anyone got any tips on how to go about doing this?
Edit: I cannot use the controller's Redirect
method (or anything involving a raw url. It needs to be routed either through Controller/Action
or Route
mechanisms).
When returning from an action you probably use RedirectToAction() you can pass in the route values.
You can have route like this
routes.MapRoute(
"DisplayDivsRoute",
"{controller}/{action}/{focusedDivId}", // URL with parameters
new {controller = "Content", action = "Display", focusedDivId = "1"}, null );
When in your Post action (when you are saving the new content object) you can then
return RedirectToAction()
HTH
Sorry for wasting everyone's time...
I just remembered that you can separate route segments with other character literals than '/',
so naturally I can build a route like this:
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{id}#{locid}",
new { ... });
Problem solved.
In MVC 3, you can use the fragment argument in this Html.ActionLink overload function:
public static MvcHtmlString ActionLink( this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string protocol, string hostName, string fragment, Object routeValues, Object htmlAttributes )
http://msdn.microsoft.com/en-us/library/dd460522.aspx
You've pretty much answered your own question. Redirect to a URL similar to the one you have given (http://site/Controller/Action/Id#12), and generate an anchor tag in your view with a name attribute just before the record you want to jump to.
精彩评论