Linking to location on page (#id) through ASP.NET MVC mechanisms?

纵然是瞬间 提交于 2019-12-08 13:31:43

问题


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]

<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).


回答1:


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




回答2:


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.




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/2071414/linking-to-location-on-page-id-through-asp-net-mvc-mechanisms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!