我有这个控制器代码:
public async Task<ActionResult> Contact()
{
var url = @"http://mimijumi-dev.myshopify.com/blogs/news.atom";
string result;
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage(HttpMethod.Get, url);
var response = await httpClient.SendAsync(request);
result = response.Content.ReadAsStringAsync().Result;
}
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(result);
XmlNodeReader xreader = new XmlNodeReader(xdoc);
XmlSerializer deserializer = new XmlSerializer(typeof(RssFeedModel));
RssFeedModel rssFeedItem = (RssFeedModel)deserializer.Deserialize(xreader);
xreader.Close();
xreader.Dispose();
return View(rssFeedItem);
}
deserializer
填充这些模型:
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class RssFeedModel
{
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("content")]
public string Content { get; set; }
[XmlElement("link")]
public List<Link> link { get; set; }
[XmlElement("entry")]
public List<Entry> entry { get; set; }
}
[XmlRoot("link")]
public class Link
{
[XmlAttribute("rel")]
public string rel { get; set; }
[XmlAttribute("type")]
public string type { get; set; }
}
[XmlRoot("entry")]
public class Entry
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("published")]
public DateTime PublishDate { get; set; }
}
视图非常简单,因为它只是试图显示entry
元素的数量:
@Model.entry.Count
这会引发以下异常:
InvalidOperationException:传递给ViewDataDictionary的模型项的类型为“web.app.Models.RssFeedModel”,但此ViewDataDictionary实例需要类型为“System.Collections.Generic.List”1 [web.app]的模型项。 Models.RssFeedModel]”。 Microsoft.AspNet.Mvc.ViewDataDictionary.EnsureCompatible(Object value)
RssFeedModel具有列表元素,但它本身不是列表(或者不应该基于模型类)。我究竟做错了什么?感谢。
答案 0 :(得分:1)
Count只能应用于Collection或List,这里只传递单个RSS Feed Item到视图。传递RSSFeedItems列表。
public async Task<ActionResult> Contact()
{
......
List<RssFeedModel> feeds = new List<RSsFeedModel>();
XmlNodeReader xreader = new XmlNodeReader(xdoc);
XmlSerializer deserializer = new XmlSerializer(typeof(RssFeedModel));
feeds.Add((RssFeedModel)deserializer.Deserialize(xreader));
xreader.Close();
xreader.Dispose();
return View(feeds);
}