Three Value Logic
Three Value Logic

Reputation: 1112

Redirect to another action based on a variable

I have a controller which has a value. I want to redirect to an action of another controller based on the value. I have used a simple if structure but I am not sure this is the cleanest way to do this. Is there a better way to solve this problem?

My current code is below.

// Get Search Results
    [ValidateInput(false)]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Search(SearchViewModel searchViewModel)
    {
        var SelectedCategory = searchViewModel.SelectedCategory;
        var SearchText = searchViewModel.SearchText;

        if (SelectedCategory == 1)
        {
            return RedirectToAction("Artists", "Search");
        }
        else if (SelectedCategory == 2)
        {
            return RedirectToAction("Albums", "Search");
        }
        else
        {
            return RedirectToAction("Tracks", "Search");
        }
    }

Upvotes: 1

Views: 564

Answers (3)

anar khalilov
anar khalilov

Reputation: 17498

I don't think there is a much better solution than what you already have provided. Only small tips here and there:

  1. As a naming convention rule, local variables should be named with small case. See how SO syntax highlighter colored your local variable names as if they were class names.
  2. If the only purpose of your if ... else if ... else is to do different things depending on the value of a variable (as it is in your code), it is better to use a switch statement.

Other than that, I don't think your code is in any way "bad".

EDIT By the way, if you are looking for a one-liner version (but less readable):

[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search(SearchViewModel searchViewModel)
{
    return RedirectToAction(searchViewModel.SelectedCategory == 1 ? "Artists" : searchViewModel.SelectedCategory == 2 ? "Albums" : "Tracks", "Search");
}

Upvotes: 2

blez
blez

Reputation: 21

I believe I've answered too fast. Anyway, I suppose that Category is an enum (if it is not maybe it should be), so you can add an attribute like this:

public enum Category {
    [RelatedAction("Artists")]
    Artists,
    [RelatedAction("Albums")]
    Albums,
    [RelatedAction("Tracks")]
    Tracks
}

and then you will have only one line inside Search method:

return RedirectToAction(searchViewModel.SelectedCategory.GetRelatedAction(), "Search");

Upvotes: 2

Adrian Thompson Phillips
Adrian Thompson Phillips

Reputation: 7141

You could use a switch statement:

string action;

switch (selectedCategory)
{
    case 1:
        action = "Artists";
        break;
    case 2:
        action = "Albums";
        break;
    default:
        action = "Tracks";
        break;
}

return RedirectToAction(action, "Search");

Upvotes: 1

Related Questions