这是我的第一篇文章.
因此,我遇到了这个问题,并且对这种语言或C#还是陌生的.
我有一个读取新闻rss的模型,然后使用相同的索引控制器将其传递给视图.
这是我的模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml.Linq;
namespace Fantacalcio.Web.Areas.Admin.Models
{
public class FeedGazzetta
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public string PubDate { get; set; }
public string Image { get; set; }
}
public class ReadFeedGazzetta
{
public static List<FeedGazzetta> GetFeed()
{
var client = new WebClient();
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
var xmlData = client.DownloadString("http://www.gazzetta.it/rss/Calcio.xml");
XDocument xml = XDocument.Parse(xmlData);
var GazzettaUpdates = (from story in xml.Descendants("item")
select new FeedGazzetta
{
Title = ((string)story.Element("title")),
Link = ((string)story.Element("link")),
Description = ((string)story.Element("description")),
PubDate = ((string)story.Element("pubDate")),
Image = ((string)story.Element("enclosure").Attribute("url"))
}).Take(10).ToList();
return GazzettaUpdates;
}
}
}
我的控制器如下:
public ActionResult Index()
{
IndexAdminVm model = new IndexAdminVm();
//List<FeedGazzetta> ListaNotizie = new List<FeedGazzetta>();
model.ListaNotizie = ReadFeedGazzetta.GetFeed();
return View(model);
}
我的ViewModel是这样的:
public class IndexAdminVm
{
public List<FeedGazzetta> ListaNotizie { get; set; }
}
我的看法是这样的:
@model List<Fantacalcio.Web.Areas.Admin.Models.IndexAdminVm>
@{
ViewBag.Title = "Home";
}
<h2>Home</h2>
@foreach (var item in Model)
{
@item.ListaNotizie.FirstOrDefault().Title <br />
@Html.Raw(item.ListaNotizie.FirstOrDefault().Description) <br />
@item.ListaNotizie.FirstOrDefault().Image <br />
@Convert.ToDateTime(item.ListaNotizie.FirstOrDefault().PubDate) <br />
@item.ListaNotizie.FirstOrDefault().Link <br />
<br /><br />
}
编译时不会出现任何错误,但是当我在网上检查时,我是从视图中得到的:
传递到字典中的模型项的类型为’Fantacalcio.Web.Areas.Admin.Models.IndexAdminVm’,但是字典中需要类型为’System.Collections.Generic.List`1 [Fantacalcio.Web. Areas.Admin.Models.IndexAdminVm]’.
怎么了?
我希望我很清楚:)
谢谢
解决方法:
您将错误的模型传递给View.
您传递了单个IndexAdminVm,但需要该视图模型的列表.您应该将视图更改为:
@model Fantacalcio.Web.Areas.Admin.Models.IndexAdminVm
...
@foreach (var item in Model.ListaNotizie)
...