Reputation: 611
Usin ASP.NET I am trying to add a list of profiles to a object in a model and then enumerate over this list in the view.
public ActionResult Index(BlogPage currentPage)
{
var model = new BlogPageModel(currentPage);
var pages = new List<BlogPage>();
var profilePages = new List<ProfilePage>();
if (currentPage.ProfileArea != null)
{
foreach (LinkItem linkItem in currentPage.ProfileArea)
{
var page = _pageDataHelper.GetPageData(linkItem);
var profilePage = page as ProfilePage;
if (profilePage != null)
{
profilePages.Add(profilePage);
}
}
model.Profiles = profilePages;
}
return View(model);
}
Using this code in the view:
@foreach (ProfilePage profile in Model.BlogPages)
{
@Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
}
However above code returns the error:
CS0030: Cannot convert type 'Models.Pages.BlogPage' to 'Models.Pages.ProfilePage'
Can someone point me the correct way to store a list inside a model and render this nested object in a view?
Thanks!
Upvotes: 0
Views: 62
Reputation: 2764
You have a typo in your foreach
loop:
@foreach (ProfilePage profile in Model.BlogPages)
{
@Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
}
You are looping over the property BlogPages
not the property Profiles
that you set with a ProfilePage
collection in your controller:
var pages = new List<BlogPage>();
var profilePages = new List<ProfilePage>();
if (currentPage.ProfileArea != null)
{
...shortened for length...
model.Profiles = profilePages; // Right here is what you intended to loop over
}
Upvotes: 1
Reputation: 1612
Hi Its seems that you have problem in the for each loop,but i couldn't exactly figure out the problem line, since model is not available above.
Answer to your question:
Can someone point me the correct way to store a list inside a model and render this nested object in a view?
ex:
public class somemodelname
{
public list<anytype> somepropertyname{get;set;}
}
accessing:
@foreach (var singlevalueOrObj in Model.somepropertyname)
{
@Html.Partial("../ProfilePage/Index", new PageViewModel<singlevalueOrObj >(profile))
}
In the above way you can store any list object inside your model and for rendering the page as same way as you did in the above that is using the partial view.
Hope above information was helpful.
Thanks
Karthik
Upvotes: 1