Hary
Hary

Reputation: 5818

Switch Case in Razor based on parameters

I am implementing tabbed view in mvc4. So i implemented partial view which in turn called in every view for tabbed structure. The below code set active tab based on the parameter passed from the view.

<ul class="nav nav-tabs">
@{ var UserFocus = ""; var CardFocus = ""; var CarrierFocus = ""; }
@{
switch(ViewData["ActiveMenu"].ToString())
{
    case "User":
        UserFocus = "active";
        break;
    case "Card":
        CardFocus = "active";
        break;
    case "Carrier":
        CarrierFocus = "active";
        break;   
}
}
   <li class="@UserFocus">User view link</li>
   <li class="@CardFocus">card view link</li>
   <li class="@CarrierFocus">Carrier view link</li>
</ul>

And in every view it will called like this based on the view

@Html.Partial("_AdminSettings", new ViewDataDictionary {{ "ActiveMenu", "User" }} )

This is working fine.

  1. I am sure whether the implementation is a standard practice ?
  2. Any other easy way for this implementation ?

Upvotes: 4

Views: 6574

Answers (1)

Darren
Darren

Reputation: 70748

Personally I do not like logic in the view. As a rule of thumb I generally put the logic in the model and pass it down to the view and believe the view is there to display how the data should look, not manipulate the data.

As an alternative approach you could have a Navigation Model and pass:

ViewData["ActiveMenu"]

to your controller and populate the Navigation Model.

public class NavigationModel 
{
    public string UserFocus { get; private set; } 
    public string CardFocus { get; private set; }
    public string CarrierFocus { get; private set; }

    public NavigationModel(string ActiveMenu)
    {
       // Your switch statement to populate the properties.
    }
}

Your view would look like this:

@Model NavigationModel

<ul class="nav nav-tabs">
  <li class="@Model.UserFocus">User view link</li>
  <li class="@Model.CardFocus">card view link</li>
  <li class="@Model.CarrierFocus">Carrier view link</li>
</ul>

Which in my opinion is cleaner.

Upvotes: 4

Related Questions