0

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!

3
  • There is something amiss in your design of the site. You need a proper data layer/service which can be reused in your web api, as well as your, mvc form. Commented Feb 9, 2014 at 9:32
  • I disagree - my api controller returns the result I want to, my question is how do I format the response. Commented Feb 9, 2014 at 10:54
  • Yep. You can use json serialization/de-serialization libraries like Json.NET, or JavaScriptSeralizer (native to the .net framework), etc. Most of the answers here already describe this. You make use of the library in the controller action method, pass the models to the view. Earlier, I was simply laying emphasis on having a uniform way to fetch data. Commented Feb 9, 2014 at 11:07

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

My API response is fine, I'm just not sure how to format it once I get it
0

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(...)

$.each takes a function (element, key) { }

but

$("...").each takes a function (key, element) { }

this has caused me some headaches.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.