Darthg8r
Darthg8r

Reputation: 12675

Site wide Tag Cloud

I've created a tag cloud partial view for my site. The partialview is to be included on all pages on the site. The data comes from a database. Is there a way to run the code that lives in the controller globally, so I don't have to put it on every single action of every single controller?

I'd like to avoid putting this on every action:

public ActionResult Index()
{
    ViewData["Tags"] = Tags.GetTags();
    return View();
}

and

public ActionResult Index()
{
    return View(Tags.GetTags());
}

It'd be a nightmare if I ever had to change that code. There has to be a better way of handling database bound content that is on every page of a site.

Upvotes: 1

Views: 109

Answers (2)

aligray
aligray

Reputation: 2832

You could always use the ViewModel pattern and have a base ViewModel class for all your actions:

public abstract class ViewModelBase
{
    public IEnumerable<Tag> Tags { get; private set; }

    public ViewModelBase()
    {
        Tags = GetTagsFromDatabase();
    }
}

Then just make every subsequent ViewModel inherit this base class.

public HomeViewModel : ViewModelBase
{
    ...
}

And then in your Controller action:

public ActionResult Index()
{ 
    var viewModel = new HomeViewModel();
    return View(viewModel);
}

Hope this helps.

Upvotes: 3

6nagi9
6nagi9

Reputation: 544

You can put your global code either in your MasterPage, or you also make a custom control out of your code and reuse it in the pages that need that code.

Upvotes: 0

Related Questions