Displaying list data from a RESTful web service (C#)

Created: 2015-12-10 17:44 Updated: 2015-12-10 19:30 Notebook: All Tech/Reference
There is more than one way to display a list of data (e.g. tasks, contacts, messages, meetings, etc) from a RESTful web service.  There are pros and cons to each.  Here is an example that uses C#. 

  1. The server side Web application developer may propose writing a factory (or service) to retrieve the data (via HTTP get/post), parse the results and instantiate a list of objects from those results.  
    // C# HTTP GET
    public List<Contact> GetContacts() {
        var contacts = new List<Contact>();
        HttpResponseMessage response = await client.GetAsync(“api/contacts");
        if (response.IsSuccessStatusCode)
        {
            contacts = await response.Content.ReadAsAsync<List<Contact>>();
        }
        return contacts; 
    }
    If using MVC (hopefully this is the case), the call to this service would be made by the controller.  The controller would load the list of objects into all (or part) of the model and return the model-data to the view.  
    // C# HTTP GET
    using
     System.Web.Mvc;

    namespace MvcApplication1.Controllers
    {
       
    [HandleError]
       
    public class ContactsController : Controller
       
    {
           
    public ActionResult Index()
           
    {
                var model = new MyModel();
                model.Contacts = GetContacts()
               
    return View(model);
           
    }
       
    }
    }
    The view engine would render the view (HTML + model references) by replacing references to the data with their values.  The developer may choose a div based grid system for maximum flexibility.  This example uses a partial view.
    <div class="container-fluid">
    @foreach(var person in Model.Contacts) {
      <div class="row">

        <div class="col-xs-6 col-sm-4">
          (@person.Id) @person.Name
       
    </div>
        <div class="col-xs-6 col-sm-4">
          @person.birthdate
       
    </div> 
        <div class="col-xs-6 col-sm-4">
          @person.EmailAddress
       
    </div>
      </div>
    }

    </div>

View static HTML