user3027634
user3027634

Reputation:

Encapsulation switch logic in asp.net mvc controller

I try to improve the following code. The problem is that the method Handle become cumbersome. I'm looking for a way to exclude addition and handle commands from the main method. I would like to ActionResult HandleCommand method became closed to changes by adding new commands. So, I'm not thrilled with a large switch block. I would be happy to receive any suggestions.

    [HttpPost]
    public ActionResult HandleCommand(string command)
    {
        switch (command)
        {
            case "foo":                    
                DoSomthing();                    
                return View("someView1");

            case "bar":
                DoSomthingElse(); 
                return RedirectToAction("someAction");

            case "fooBar":                
                return File("file.txt", "application");
            //...

            default:
                //...
                return new HttpStatusCodeResult(404);

        }
    }

Upvotes: 2

Views: 2238

Answers (1)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7846

Your method can be redone to the following:

  public ActionResult HandleCommand(string comand)
  {
    CommandAction Comand = commandHandler[comand] ?? new CommandAction(method, new HttpStatusCodeResult(404));
    Comand.DoSomthing();
    return Comand.Result;
   }

If you make some changes:

 public class CommandAction
 {
   public Action DoSomthing { get; set; }
   public ActionResult Result { get; set; }

   public CommandAction(Action action, ActionResult actionResult)
   {
      DoSomthing = action;
      Result = actionResult;
   }            
 }


public class SomeController : Controller
{       
  public Dictionary<string, CommandAction> commandHandler
  {
    get
    {
      return new Dictionary<string, CommandAction>()
      {
        {"foo",    new CommandAction( DoSomthing, View("foo"))},
        {"foo",    new CommandAction( DoSomthingElse, RedirectToAction("someAction"))},
        {"fooBar", new CommandAction( SomeMethod, File("file.txt", "application"))}  
      };
    }

    }

And, when you add new commands Modify commandHandler

Upvotes: 2

Related Questions