如何很好的与HTML的ASP.NET Web API格式JSON的返回值? [英] How to format JSON return value in nice HTML with ASP.NET web api?
问题描述
这是使用MVC网页API 2我第一次和我设法把我的web应用程序检索我JSON格式需要从一个单独的域第2个Web应用程序中的数据。
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.
我的API控制器看起来是这样的:
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;
}
我的问题是,我试图格式化结果JSON的CSS / HTML - 如果我直接从数据库中获取,而不是通过API数据,剃刀看法是这样的:
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>
我如何格式化我的JSON结果匹配这种格式?我该怎么错了路,我应该使用RSS源,而不是在一个API调用?
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?
感谢您的帮助!
推荐答案
I have had decent results with NewtonsoftJSON
此外,注意,当你调用 $。每个(...)
,参数回调从 $逆转( #ID)。每个(...)
Also, be advised that when you call $.each(...)
, the parameters to the callback are reversed from $("#id").each(...)
$.each takes a function (element, key) { }
但
$("...").each takes a function (key, element) { }
这令我有些头疼。
这篇关于如何很好的与HTML的ASP.NET Web API格式JSON的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!