views:

936

answers:

3

In asp.net MVC I have a search action in my controller and I am trying to decide If I should pass the query to my repository as a string

public ActionResult Search(string query)
{
    return View(_repository.ListPeople(query));
}

or as individual parameters:

public ActionResult Search(string FirstName, string LastName, System.Nullable<byte> Education)
{
    return View(_repository.ListPeople(FirstName, LastName, Education));
}

A lot of examples I have seen online use the query string method, but to me it doesn't feel as "safe", even though it's a little easier to deal with when you have a bunch of parameters to pass in. Is there a general consensus as to the better way to do this?

+2  A: 

I would favour model binding. That way if you decide to add extra search options you have no changes to make apart from the model class.

Info here and here

redsquare
This seems to be the cleanest approach, I used model binding elsewhere I'm not quite sure why I didn't think to use it in this situation as well. Thanks!
Graham
+1  A: 

I would most definitely suggest going with the second route. There's no need to couple your controller with your repository. Let your repository be in charge of getting data, it shouldn't have to do any kind of parsing of a query string. That's not its job. Let the controller deal with that.

BFree
+2  A: 

Personally, I prefer to not have the repository take on the responsibility of parsing a query string. Looking at it from a separation of concerns point of view, I feel that the repository should remain implementation-agnostic. Having to create query strings for unit testing, for example, is more cumbersome than calling the method directly with parameters.

That being said, I also prefer to have controllers interface with well-defined services, as well, as it helps to keep the controllers lighter, in my experience. I try to let the service act as a gateway to the repository, although there is no requirement to do so. There are two things that I will pass into a repository (or more likely, service), depending upon what the purpose of the call is - either a set of parameters, like you give in your second example, or as a constructed domain object, if applicable.

joseph.ferris