1

I am starting to switch over my Controllers to use model binders for GET actions instead of using an int parameter. My normal controller GET action looks like the following ...

public ActionResult Details(int id)
{
    DomainModel model = repository.GetById(id);
    if (model == null)
    {
        throw new HttpException(404, "Item does not exist")
    }

    //Continue along with our controller action
}

When switch to a ModelBinder I wanted to throw the HttpException in the BindModel method, however I am unsure if it is considered a good programming practice. Is the controller responsiblity for throwing the 404 or the ModelBinder?

4
  • Why you want to switch the controller actions from int?
    – VJAI
    Jun 26, 2012 at 16:36
  • @Mark So I don't have to keep writing queries to the database to get the model by the id Jun 26, 2012 at 16:39
  • But anyway you have to hit the database to get the details right?
    – VJAI
    Jun 26, 2012 at 16:41
  • @Mark yeah this will just reduce the amount of code in my controller actions. I will still have to hit the database. Jun 26, 2012 at 16:45

2 Answers 2

1

Model binding does just that, binds the model. if the model doesn't exist it would return either null or a Null Object. The controller could then decide what to do with the model. If it's null, throw.

however if you you see the same lines of code appearing than it's a good idea to encapsulate that code. One option would be to use an ActionFilter. the model binder creates the objects and the action filter can set the response code to 404 if the model is null.

in this scenario your controller only needs to worry about the "happy path". That is the model exists.

-1

So you have a GET action that returns a model based upon it's id. As per the principle of MVC it's the controller's job to interact with the model and get the corresponding instance for the id. I don't think it's a good idea to do that work in the model binder and feed the model to the controller action and it's like taking the core job away from the controller.

If you change the Details action into,

public ActionResult Details(DomainModel model)
{
}

It looks to someone you are feeding the model from outside to the action but it is supposed that action should return the model as a view or json result. Think about unit-testing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.