How to use RedirectToAction to redirecto to a position in the page?

一个人想着一个人 提交于 2019-12-11 02:57:30

问题


I am using MVC4, C# and visual studio ultimate 2013 in a project.

I am redirecting a user to an index page after submiting a form. However, this webpage has 2 tabs, and I want to redirect the user to the second tab, instead of the first one.

I have a Controller called Material, with an Index action, which sends the user to the Index View.

public ActionResult Index()
{
   return View();
} 

This View is made of two partial Views, _Materials and _Packages.

@{
    ViewBag.Title = "Index";
}
<div class="tabbable">
    <ul class="nav nav-tabs">
        <li class="active"><a href="#Materials" data-toggle="tab">Materials</a></li>
        <li><a href="#Packages" data-toggle="tab">Packages</a></li>
    </ul>
    <div class="tab-content">
        <div class="tab-pane active" id="Materials">
            @Html.Action("Materials", "Material")
        </div>
        <div class="tab-pane" id="Packages">
            @Html.Action("Packages", "Package")
        </div>
    </div>
</div>

After performing a serie of actions in another section of the application, I which to redirect the user to the /Material page, to the second tab, but I have no idea how to do it !

Currently I am using this code, which always redirects to the first tab:

return RedirectToAction("Index", "Material");

How can I fix my problem?


回答1:


You can't use something like RedirectToAction because it does not have any capability of appending a URL fragment. What you can do is use something like Redirect which just takes a URL string, and then use the URL helper to still dynamically generate the action URL for you:

return Redirect(Url.Action("Index", "Material") + "#Package");

In other words, Url.Action will generate the main URL for you and return it as a string. You can then append the fragment to this string before finally redirecting.




回答2:


You'll want to use the

Redirect method

Redirect("www.sitename.com/material/index#Package");

or

string fragment = "Package";
Redirect("www.sitename.com/material/index#" + fragment);

The #Package is what is called a Fragment Identifier, that will focus your browser on the part of the page with the id of Package.




回答3:


You can simply write an Ajax call to pass to the controller and in case of success, append #tab to the url parameter. for example use this:



来源:https://stackoverflow.com/questions/26718722/how-to-use-redirecttoaction-to-redirecto-to-a-position-in-the-page

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