c# - MVC Multiple Models in One View -
i want reach multiple models in 1 view. have dal folder , dbcontext.
class cvcontext : dbcontext { public cvcontext() : base("cvcontext") { } public dbset<linkmodel> links { get; set; } public dbset<aboutmodel> abouts { get; set; } public dbset<portfoliomodel> portfolios { get; set; } public dbset<skillmodel> skills { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.conventions.remove<pluralizingtablenameconvention>(); } }
and homecontroller
public class homecontroller : controller { private cvcontext db = new cvcontext(); public actionresult index() { return view(db.links.tolist()); } }
index.cshtml
@model ienumerable<mvccv.models.linkmodel> <ul> @foreach (var item in model) { <li> <a href="@html.displayfor(modelitem => item.linkurl)"> @html.displayfor(modelitem => item.linkname) <span class="icon"></span> <span class="menu-icon"> <img src="@url.content(item.linkimage)" alt="" /> </span> </a> </li> } </ul>
how can reach models? use foreach item in model links. thanks.
you should create view model follows:
public class fooviewmodel { public ienumerable<linkmodel> links { get; set; } public ienumerable<aboutmodel> abouts { get; set; } public ienumerable<portfoliomodel> portfolios { get; set; } public ienumerable<skillmodel> skills { get; set; } }
then controller populate them requirements, example:
public actionresult index() { var model = new fooviewmodel(); model.links = db.links.tolist(); model.abouts = db.abouts.tolist(); model.portfolios = db.portfolios.tolist(); model.skills = db.skills.tolist(); return view(model); }
then change model in view fooviewmodel
, properties available in there.
@model fooviewmodel <ul> @foreach (var item in model.links) { <li> @item </li> } </ul> <ul> @foreach (var item in model.links) { <li> @item </li> } </ul> // ....etc, change outputs needed.
Comments
Post a Comment