Reputation: 459
this is my first post. So I have this problem and I'm very new to this language or c#.
I have a model that reads the news rss, then using the same index controller I have to pass it to a view.
This is my model:
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;
}
}
}
My controller is as follows:
public ActionResult Index()
{
IndexAdminVm model = new IndexAdminVm();
//List<FeedGazzetta> ListaNotizie = new List<FeedGazzetta>();
model.ListaNotizie = ReadFeedGazzetta.GetFeed();
return View(model);
}
My ViewModel is this:
public class IndexAdminVm
{
public List<FeedGazzetta> ListaNotizie { get; set; }
}
And my view is this:
@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 />
}
In compiling do not get any error, but when I check on the web, I get this from the view:
The model item passed into the dictionary is of type 'Fantacalcio.Web.Areas.Admin.Models.IndexAdminVm', but the dictionary requires a model item of type 'System.Collections.Generic.List `1 [Fantacalcio.Web. Areas.Admin.Models.IndexAdminVm] '.
What is wrong?
I hope I was clear :) thanks
Upvotes: 3
Views: 4022
Reputation: 5632
You're passing wrong model to View.
You pass single IndexAdminVm
but expects List of this view models. You should change your view to this:
@model Fantacalcio.Web.Areas.Admin.Models.IndexAdminVm
...
@foreach (var item in Model.ListaNotizie)
...
Upvotes: 3