This is my first time using MVC Web Api 2 and I've managed to have my web application retrieve the data I need in JSON format from a 2nd web application on a separate domain.
My API controller looks like this:
private IQueryable<ArticleDTO> MapArticles()
{
return from p in db.Articles.Include("Tags")
select new ArticleDTO() {
ArticleID=p.ArticleID,
Title = p.Title,
Subheading = p.Subheading,
DatePublished = p.DatePublished,
Body = p.Body,
Tags = Tags.Select(t => new TagDTO {
Name = t.Name
})
};
}
public IEnumerable<ArticleDTO> GetArticles()
{
return MapArticles().AsEnumerable();
}
And my client side end point looks like this (mainly for testing):
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
$('<li>', { text: formatItem(item) }).appendTo($('#articles'));
});
});
});
function formatItem(item) {
return item.Title;
}
My problems is that I'm trying to format the resulting JSON in CSS/html - if I get the data directly from the database, instead of via the API, the Razor view looks like this:
<div class="col-md-8">
<h3>
@Html.ActionLink(@item.Title, "ArticlesDetail", "Home", new { id = item.ArticleID }, null)
</h3>
<span class="sidebardate">@item.Date.ToLongDateString()</span><br />
@if (item.Tags != null && item.Tags.Count > 0)
{
<span class="sidebarabstract ArticleTags">
<strong>Tags:</strong>
@Html.Raw(string.Join(", ", from category in item.Tags select string.Format("<span><a href='/Article/Category/{0}'>{1}</a></span>", category.Name, category.Name)))
</span>
}
<div class="Articlesbodytext">
<p>@item.Abstract </p>
</div>
</div>
How do I format my JSON result to match this format? Am I going down the wrong path, should I be using an RSS feed instead on an API call?
Thanks for your help!
First, you are not going wrong with web API. Second, use Fiddler (get it from here) and inspect your Web API response. Based on what you will find there adjust your WebAPI or Javascript.
I have had decent results with NewtonsoftJSON
Also, be advised that when you call
$.each(...)
, the parameters to the callback are reversed from$("#id").each(...)
but
this has caused me some headaches.