Displaying list data from a RESTful web service (C#)
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#.
- 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 GETIf 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.
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;
}// C# HTTP GETThe 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.
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);
}
}
}<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>