Lawrence
Lawrence

Reputation: 447

ASPNET MVC3 Generics with Controllers and Views

I've been trying to come up with an extensible search pattern for an mvc site I'm working on and I wanted some base functionality to minimize what I need to do to extend the search by adding another controller option.

I'm having a problem determining where I would go from having a base abstract searchable controller that presumes a particular entity and model type. The Mapper reference refers to AutoMapper and just maps the entity to the model. Everything seems to work ok but I'm not sure what the view would look like in terms of the model definition because the type is variable for the base model SearchModel. I could implement my own view in each controller with the @model SearchModel but I'm just wondering how much "free" plumbing I can get away with.

public abstract class SearchableController<TModel, TEntity, TRepository> : Controller where TRepository : ISearchableRepository<TEntity> where TEntity : class where TModel : class
{
    protected TRepository _repository;

    [HttpGet]
    public ActionResult Search(string q, int? page)
    {
        int pageNumber = page.HasValue ? page.Value : 1;
        PagedList<TEntity> entities = _repository.Search(q, 10, page);

        Mapper.CreateMap<TEntity, TModel>();
        var results = new List<TModel>();
        foreach (TEntity entity in entities)
        {
            var entityModel = Mapper.Map<TEntity, TModel>(entity);
            results.Add(entityModel);
        }

        var model = new SearchModel<TModel>();
        model.searchPattern = q;
        model.pageNumber = pageNumber;
        model.Results = new StaticPagedList<TModel>(results, entities.PageNumber, entities.PageSize, entities.TotalItemCount);

        return View(model);
    }
}

Upvotes: 0

Views: 348

Answers (2)

Lawrence
Lawrence

Reputation: 447

Yeah I think that is the route I ended up with. Then I just use a master view that handles the common view portion of the search model like the search pattern rebind to a search input, pagination, current page number etc...

Upvotes: 0

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93464

I guess I don't really understand your problem.

Your model would be an @model SearchModel<WhateverYourTModelIs>. What "free plumbing" are you referring to?

Maybe i'm confused, but you have to define the static types for your derived controllers, so what is your problem with defining static type views for them?

Upvotes: 1

Related Questions