I am faced with a challenge of displaying 15 different partial views based on the user's selection from a menu tab. Essentially, I have these 15 menu tabs on one side of the page, and when a user clicks on a tab, the content related to that tab should be shown.
In addition, Knockout is being utilized in this scenario.
Upon page load, I populate 15 Knockout observables (
self.tab_A(), self.tab_B(), ...self.tab_N()
) with data.
The code structure looks something like this: Here is the view.
<ul id="tabs">
<li>
<a data-bind="click: function(){ $root.ShowHideDiv(tab_A.id); }" style="cursor: pointer;">
Tab A
</a>
</li>
<li>
<a data-bind="click: function(){ $root.ShowHideDiv(tab_B.id); }" style="cursor: pointer;">
Tab B
</a>
</li>
...
...
</ul>
The partial views are pre-loaded but hidden from user view.
<ul>
<li id="tab_A" style="display: none" class="hiddenDivs">
@{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
</li>
<li id="tab_B" style="display: none" class="hiddenDivs">
@{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
</li>
</ul>
Displaying div using script on click event.
self.ShowHideDiv = function (tabToShow) {
console.log(tabToShow);
$('.hiddenDivs').html('');
$('#' + tabToShow).show();
};
Everything works well for 3-4 views, however the design breaks for the remaining views, possibly due to too many hidden divs.
Considering this issue, I attempted loading specific views at runtime rather than pre-loading them all. When a user selects a tab, the corresponding partial view is fetched and displayed.
My attempt:
self.ShowHideDiv = function (tabToShow) {
$('.hiddenDivs').html('');
var view = getValueFromDict(dict, tabToShow);
$('.hiddenDivs').load('/Claims/ReturnPartialView/?partialViewName=' + view);
};
This approach failed as there was no associated Action/Controller for the views, hence loading the view directly using javascript/jquery was not possible.
Another alternative I explored was creating a controller to return a partial view.
public ActionResult ReturnPartialView(string partialViewName)
{
return PartialView(partialViewName);
}
And calling it like this:
self.ShowHideDiv = function (tabToShow) {
$('.hiddenDivs').html('');
var view = getValueFromDict(dict, tabToShow);
$('.hiddenDivs').load('/MyController/ReturnPartialView/?partialViewName=' + view);
}
Although this method successfully loads the desired view, the KnockOut observable linked with that view appears as null.
I have heard about KO templates which could potentially solve this problem, yet I haven't explored them fully (but I plan to do so next). If anyone has an alternative solution without utilizing KO templates, I would appreciate the insights.
Thank you for your patience in understanding my situation.