Kinexus
Kinexus

Reputation: 12904

Run single method from Multiple Actions in MVC controller

I have the following code that is identical across multiple Action Methods in my controller. Is it possible to reduce this down to a single method and route multiple Actions to it?

[HttpGet]
public ActionResult Tool2(Guid? id)
{
    var model = _viewModelFactory.CreateViewModel<Guid?, ToolsViewModel>(id);

    return model.ReferenceFound ? View(model) : View("~/Views/Tools/InvalidReference.cshtml", model);
}

[HttpGet]
public ActionResult Tool1(Guid? id)
{
    var model = _viewModelFactory.CreateViewModel<Guid?, ToolsViewModel>(id);

    return model.ReferenceFound ? View(model) : View("~/Views/Tools/InvalidReference.cshtml", model);
}

Each Action does has a unique View and this needs to be retained.

Upvotes: 0

Views: 256

Answers (1)

Jasen
Jasen

Reputation: 14250

Make a common method which both actions will call. Leave both actions separate as it will be clearer to understand than to write (and read!) custom routes.

public ActionResult Tool1(Guid? guid)
{
    return CommonAction(guid, "Tool1");
}

public ActionResult Tool2(Guid? guid)
{
    return CommonAction(guid, "Tool2");
}

private ActionResult CommonAction(Guid? guid, string viewName)
{
    var model = _viewModelFactory.CreateViewModel<Guid?, ToolsViewModel>(id);
    return model.ReferenceFound ?
        View(model) : View("~/Views/Tools/InvalidReference.cshtml", model);
}

Upvotes: 2

Related Questions