0

I'm a little late to the MVC game and frankly there is so much information out there, it's almost impossible to use the "right" keywords to even get close to an answer.

I have a function that gets codes from the database and displays them in an auto-complete list. I want to share this GetCodes method between Controllers and these codes are used on other forms.

What is the best MVC practice for this?

Is it better to make a base class with this function, or is it better to create a Web API Controller to share these type of methods?

[Edit] To clarify, the codes I'm providing auto-completing for are like a list of cities in a large state or province. It's a static list that is only updated by the government when a change happens at the federal level.

I just don't want to cut/paste the function that performs the search, I'd rather write something that is reusable. Right now, the function GetCodes lives on one Controller and I call that controller Action method from other parts of the site. I don't like this and I'm looking for some advise on how to use other parts of ASP.NET to accomplish this in a better more robust way.

Thank you

Chris
  • 6,702
  • 8
  • 44
  • 60

2 Answers2

0

Use view models - create a view model (or view model base class) that either loads the codes or provides a method to load the codes, then use this view model as a property of larger view models (or inherit from the view model).

Moho
  • 15,457
  • 1
  • 30
  • 31
0

Any time you say "what's the best way to..." the answer is always "It depends on a lot of factors".

We don't really know much about your design, requirements, implementation, or other details. However, there are some things to keep in mind.

There is no reason to create a WebApi controller if you don't need to a distributed architecture of any kind.

It sounds like your data is simply a part of your model, as such you can use any of the standard patterns for data access of model data. Any tutorial, such as MVC Music store or Nerd Dinner will show you how to do this.

Just because data is shared between controllers doesn't make it special.. the whole point of a model is that data can be used by any controller.

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291