patternhtmlMinor
Avoiding redundant code in MVC view page
Viewed 0 times
mvcviewredundantpagecodeavoiding
Problem
Based on the true condition, I am making some operations. But I want to simplify the below HTML code in a better way.
@{
bool savingHtml = (Request.QueryString["savehtml"] == "1");
string activeTab = Request.QueryString["from"];
}
@if (savingHtml)
{
if (activeTab.ToLower() == "index")
{
- Heat Map
Table
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
}
else{
Heat Map
- Table
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
}
}
else
{
- Heat Map
Table
@Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model)
}
Solution
Most of your code is duplicated, what I did is extract the logic to the first code block, and left only the placeholders in the HTML.
@{
bool savingHtml = (Request.QueryString["savehtml"] == "1");
string activeTab = Request.QueryString["from"];
string tabContent = Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model);
string heatClass, tableClass;
string tableId = "table";
string heatId = "heat";
string heatTabContent, tableTabConten;
if (savingHtml && activeTab.ToLower() != "index") {
heatClass = "active";
heatTabContent = tabContent;
tableId += "2";
heatId += "2";
} else {
tableClass = "active";
tableTabContent = tabContent;
if (savingHtml) {
tableId += "1";
heatId += "1";
}
}
}
Heat Map
Table
@tableTabContent
@heatTabContent
- Note: I have no experience with ASP.Net, so I apologize if the code is not as clean as possible, or has any syntax errors... The gist of the matter is still that if you extract the logic, you get shorter and cleaner code, with much less copy+paste...
Code Snippets
@{
bool savingHtml = (Request.QueryString["savehtml"] == "1");
string activeTab = Request.QueryString["from"];
string tabContent = Html.Partial("~/Views/Shared.MultiQuery/_resultset.cshtml", Model);
string heatClass, tableClass;
string tableId = "table";
string heatId = "heat";
string heatTabContent, tableTabConten;
if (savingHtml && activeTab.ToLower() != "index") {
heatClass = "active";
heatTabContent = tabContent;
tableId += "2";
heatId += "2";
} else {
tableClass = "active";
tableTabContent = tabContent;
if (savingHtml) {
tableId += "1";
heatId += "1";
}
}
}
<div class="summaryTab">
<ul class="nav nav-tabs" data-tabs="tabs">
<li class="@heatClass"><a data-toggle="tab" href="#heat">Heat Map</a></li>
<li class="@tableClass"><a data-toggle="tab" href="#table">Table</a></li>
</ul>
</div>
<div class="tab-content">
<div class="tab-pane active" id="@tableId">
@tableTabContent
</div>
<div class="tab-pane" id="@heatId">
@heatTabContent
</div>
</div>Context
StackExchange Code Review Q#43536, answer score: 2
Revisions (0)
No revisions yet.