Search code examples
asp.net-mvcasp.net-mvc-3bll

Should I call BLL methods directly into my Asp.Net MVC 3 Controller?


I have a Business Object Layer that I use in a couple of other applications and I want to use it on my MVC application. My concern is more a design concern: Is it correct to have something like the following:

using Interface.MyOtherProject
public class MyMVCController: Controller
{
    [HttpGet]
    public string GetSomethingById(Int32 id)
    {
        return new JavaScriptSerializer().Serialize(MyObject.GetById(id));
    }

}

So the question would be can I do this, should I do this in the Model instead and return this string directly from the Model or should I rewrite my BLL into my Model. I read some of the answers with similar question but it is not still clear to me if I can or cannot (rather if I should or not). I do not want to break the pattern since I will be showing this project to some companions in school.

Thanks for the help!

Hanlet


Solution

  • When we had to confront this decision, we went with creating view models that encapsulated/mirrored our business objects. This gives us more control over how the objects should look when serialized in json without having to add view logic in our business layer.

    Example: Suppose we had a Person business object:

    public class Person
    {
      public int Id {get;set;}
      public string Name {get;set;}
    }
    

    When a client is going to consume our web service, we wouldn't want them to know what the Id value is, since that's an internal database key. The two options we considered for fixing that is 1) add a [ScriptIgnore] attribute onto Person.Id property or create a separate view model for our Person, which is custom-tailored to the view domain.

    We stayed away from option 1 because we didn't want to add view logic in our business layer for much of the same reason you don't... our business layer isn't directly tied to our presentation layer.

    This is a very simplified scenario, but the larger idea is still intact. With separate view models you have the ability to include/exclude data in your view without hampering the cleanliness of your business layer.