我正在努力解决一个看起来很奇怪的问题。
1)我有一个名为“Tumblr”的课程:
public class Tumblr
{
public string BlogName { get; set; }
public dynamic PhotosCollection { get; set; }
}
2)我的控制器中有一个方法:
public ActionResult Index()
{
var model = new List<Tumblr>();
var client = new HttpClient();
var task = client.GetAsync("http://api.tumblr.com/v2/blog/puppygifs.tumblr.com/posts/photo?api_key=SbvxQcWuuNr1mfRvILKKTqiztMGvR8hbGPBDA9PlMidrYdd8Ik")
.ContinueWith((taskWithMsg) =>
{
var response = taskWithMsg.Result;
var jsonTask = response.Content.ReadAsAsync<JObject>();
jsonTask.Wait();
var jsonResponse = jsonTask.Result;
model = FillModel(jsonResponse, model)
});
task.Wait();
return View(model);
}
private List<Tumblr> FillModel(dynamic jsonObject, List<Tumblr> model)
{
var postObject = (JArray)jsonObject["response"].posts;
var posts = postObject.Select(e => new Tumblr()
{
BlogName = e["blog_name"].ToString(),
PhotosCollection = e["photos"].Select(o => new
{
Photos = o["alt_sizes"].Select(s => new
{
Width = s["width"].ToString(),
Height = s["width"].ToString(),
Url = s["width"].ToString(),
})
})
});
model.AddRange(posts);
return model;
}
这是我的观点:
@using System.Collections
@{
ViewBag.Title = "Home Page";
}
<ol class="round">
@foreach (dynamic blog in Model)
{
<li class="one">
<h5>@blog.BlogName</h5>
<span>@blog.PhotosCollection</span>
<hr />
<hr />
<hr />
@foreach (dynamic photos in blog.PhotosCollection)
{
foreach (var photo in photos.Photos)
{
<img src="@photo.Url" width="@photo.Width" height="@photo.Height"/>
}
}
<hr />
</li>
}
</ol>
当我尝试运行时,它会引发错误:
'object' does not contain a definition for 'Photos'
即使我的模型中有一个属性,我也不明白为什么它会引发错误。