Aaron Anodide
Aaron Anodide

Reputation: 17186

How to obtain same routing logic for ApiControllers as regular Controllers in ASP.NET MVC 4?

I started out with a Controller that takes filter parameters like this:

public class CampaignsController : Controller
{
    public ActionResult List(string searchstring, string pid, string country, string vertical, string traffictype)
    {
         var query = db.Campaigns;
         if(!string.IsNullOrWhiteSpace(country))
         {
              query = query.Where(c => c.CountryCode == country);
         }
         // and so on...      
         var viewModel = new CampaignListViewModel { Campaigns = query.ToList(); }
         return View(viewModel);
    }
}

What I liked about this is that actions mapped to it even if some of the parameters are null.

Then I converted over to an Ajax style and found the ApiController to be convenient as a way to generate the JSON responses I needed.

However, I have found that all of the parameters need to present in the query string in order for the route to match up to the Action.

Here is the sample code for that:

    public class CampaignsApiController : ApiController
    {
        public IQueryable<CampaignViewModel> Get(string vertical, string traffictype, string search, string country, int? pid)
        {
            var campaigns = db.Campaigns.AsQueryable();
            if (!string.IsNullOrWhiteSpace(vertical))
            {
                var cr = db.Verticals.Where(v => v.Name == vertical).FirstOrDefault();
                if (cr != null)
                    campaigns = campaigns.Where(c => c.Vertical.Name == vertical);
            }
            // and so on...
            var query = campaigns.AsEnumerable()
                       .Select(c => new CampaignViewModel(c))
                       .AsQueryable();
            return query;
        }
   }

Is it possible to obtain the same behavior for the ApiController?

Alternately, could my design approach or the way I am using the ApiController be modified in a way to coalesce the ApiController default behavior to the result I am after?

Here's the gist of the two classes for reference.

Upvotes: 1

Views: 171

Answers (1)

Turnkey
Turnkey

Reputation: 9406

Try putting in some default values for the parameters that might be missing, e.g.

public IQueryable<CampaignViewModel> Get(string vertical = null, string traffictype = null, string search = null, string country = null, int? pid = null) {

 ...

}

Upvotes: 1

Related Questions