BviLLe_Kid BviLLe_Kid - 2 months ago 19
C# Question

Redirect to Page but specific Tab

I have used this as an example of what I am trying to do.

I have a tabbed page.

In my Controller I want to redirect to a page but a specific tab on that page.

Now when I am on that page, and hover over the tab the link is

http://localhost:xxxxx/OInfoes/Details/2#phases


So in my controller I did this to try and recreate the same link:

return new RedirectResult(Url.Action("Details", "OInfoes", new { id = phase.OID }) + "#phases");


This gives me the correct link but it doesn't put me on the correct tab.

How do I get this to work?

My HTML for the tabs is below:

<ul class="nav nav-tabs">
<li class="active"><a href="#oInfo" data-toggle="tab">Information</a></li>
<li><a href="#reports" data-toggle="tab">Previous Reports</a></li>
<li><a href="#phases" data-toggle="tab">Previous/Current Phases</a></li>
</ul>

Answer

You should update your action method to take a parameter to represent the tab to be selected.

public ActionResult Details(int id,string tab="")
{
   if (id != null)
        ViewBag.ActiveTab = id.ToString();
   // to do : Return a view
}

When you return the redirect result, send a querystring with name tab

return new RedirectResult(Url.Action("Details", "OInfoes", new { id = phase.OID ,
                                                                           tab="phases"}));

Now in your document ready, use the value of ViewBag.ActiveTab value, generate the jQuery selector from that and use that to call .tab('show').

$(function () {
    var selector = '@ViewBag.ActiveTab';
    if(selector)
    {
       $("#link-tab"+selector).tab('show');
    }        
});

Make sure your tab's has id's matching with our above code.

<ul class="nav nav-tabs">
    <li class="active"><a href="#oInfo" id="link-info" data-toggle="tab">Info</a></li>
    <li><a href="#reports" id="link-reports" data-toggle="tab">Prev Reports</a></li>
    <li><a href="#phases" id="link-phases" data-toggle="tab">Prev/Cur Phases</a></li>
</ul>
Comments