woggles
woggles

Reputation: 7444

JsonResult in services layer

In my MVC3 solution I'm wondering how to move the logic that returns Json out of the controller and into the service layer. Say I have the following action in my controller to get the Json needed for a JQueryUI autocomplete control:

public JsonResult ClientAutocompleteJSON(string term)
{
    NorthwindEntities db = new NorthwindEntities();
    var customers = db.Customers
                .Where(c => c.ContactName.Contains(term))
                .Take(25)
                .Select(c => new
                {
                    id = c.CustomerID,
                    label = c.ContactName,
                    value = c.ContactName
                });

    return Json(customers, JsonRequestBehavior.AllowGet);
}

How would I move this into the service layer? I would prefer not to reference System.Web.MVC in my service layer. I've also thought of returning the customers but I'm not sure how to return the anonymous type - would I have to create a class?

Upvotes: 0

Views: 871

Answers (3)

Ben Foster
Ben Foster

Reputation: 34800

I would not couple your service implementation to a specific (UI) format. It would be better to return a strongly typed customer object and then format this how you want within your Action method.

// Service method

public IEnumerable<Customer> FindCustomers(string term) {
    NorthwindEntities db = new NorthwindEntities();
    return db.Customers
                .Where(c => c.ContactName.Contains(term))
                .Take(25)
                .ToList();
}

// Action method

public JsonResult ClientAutocompleteJSON(string term) {

    var customers = customerService.FindCustomers(term)
                        .Select(c => new
                        {
                            id = c.CustomerID,
                            label = c.ContactName,
                            value = c.ContactName
                        });

    return Json(customers, JsonRequestBehavior.AllowGet);
}

This code is much more reusable - for example, you could use the same service method to provide a simple HTML search form.

Upvotes: 2

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

I know about a feature in Ruby on Rails, there you can define that your method is capable of returning JSON or XML or HTML based on client preference, it will be a good feature if you can find a library that can do this for you. It could be an aspect which by dynamic proxifying your services can do.

Upvotes: 0

lkurylo
lkurylo

Reputation: 1641

Create a DTO object: http://martinfowler.com/eaaCatalog/dataTransferObject.html

Upvotes: 1

Related Questions