问题
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