I am new to MVC and facing one issue.
I have a xml file and i am retrieving its value using Linq to xml and assigning it to ViewData.
Controller.cs
var res=from x in doc.Descendants("person")
select new
{
Fname=x.Element("fname").Value,
Lname=x.Element("lname").Value
};
ViewData["Persons"]=res;
in View I am trying
<% foreach (var item in ViewData["Persons"])
{ %>
<li> <%= item.Fname %> </li>
<% } %>
but foreach (var item in ViewData[“Persons”] is giving type casting error..what should be the exact type csting so that i can retrive values in the format item.Fname.
Thanks.
Using
ViewData, although possible, is not the most elegant way to pass information from controller to view. Using specific view model instead makes code easier and cleaner, and resolves casting issues.Try defining model first:
Then use your model in action:
Then use your model in view:
View has to inherit from
System.Web.Mvc.ViewPage<ViewModel>.