Red
Red

Reputation: 858

Is it possible to assign multiple actions to the same controller method?

I have a simple MVC Controller that returns a list of files from folders based on View action. Index() action contains a list of Collections so then user clicks on CollectionOne, the corresponding view is populated. The same behavior is applied to other collections.

The problem is, I have a lot redundant code that I have been able to manage at certain degree by using a private ActionContent() method invoked by all actions. So whenever I have a new collection to add to website, I just add a ActionResult for this Collection and invoke ActionContent() method.

Is there any way to optimize this code to make it more dynamic, without adding a new ActionResult every time a need to post a new collection?

My controller looks like this:

public class PortfolioController : Controller
{
    public ActionResult CollectionOne()
    {
        return View(ActionContent());
    }

    public ActionResult CollectionTwo()
    {
        return View(ActionContent());
    }

    private IEnumerable<string> ActionContent()
    {
        const string folder = @"~/Content/images/portfolio/";
        var path = folder + ControllerContext.RouteData.Values["action"];

        var files = Directory
            .EnumerateFiles(Server.MapPath(path))
            .Select(Path.GetFileName);

        return files;
    }
}

I want to turn it into something like this (to avoid redundancy) using ActionNames or maybe proper route mapping:

public class PortfolioController : Controller
{
    [ActionName("CollectionOne")]
    [ActionName("CollectionTwo")]
    [ActionName("CollectionThree")]
    public ActionResult PortfolioCollection()
    {
        const string folder = @"~/Content/images/portfolio/";
        var path = folder + ControllerContext.RouteData.Values["action"];

        var files = Directory
            .EnumerateFiles(Server.MapPath(path))
            .Select(Path.GetFileName);

        return View(files);
    }
}

Upvotes: 0

Views: 1303

Answers (1)

SLaks
SLaks

Reputation: 887807

That's what parameters are for:

public ActionResult PortfolioCollection(string id)
{
    const string folder = @"~/Content/images/portfolio/";

    var files = Directory
        .EnumerateFiles(Server.MapPath(folder + id))
        .Select(Path.GetFileName);

    return View(files);
}

You can make a custom route to assign any URL pattern you want.

Upvotes: 2

Related Questions