I cannot seem to figure out how to access my Model from my View. I am confused.
Here is my Home controller. I have verified that “specimens” is being populated with data from the database:
public class HomeController : Controller
{
wildtropEntities wildlifeDB = new wildtropEntities();
public ActionResult Index()
{
ViewData["CurrentDate"] = System.DateTime.Now.ToString("MM/dd/yyyy");
var specimens = from s in wildlifeDB.specimen1
select s;
return View(specimens);
}
}
And here are couple snippets from my View:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<% foreach (WildlifeTropical.Models.specimen s in ??????)
{ %>
<div>s.Name</div>
<% } %>
I assumed I would be able to access “specimens” since I passed it to the View from the Controller (ie, return View(specimens))…but it isn’t working.
You will have to make your view strongly typed to a collection of
specimenwhich is what you are passing to it from your controller action (IEnumerable<specimen>):Notice how the view inherits
System.Web.Mvc.ViewPage<IEnumerable<WildlifeTropical.Models.specimen>>and it is now strongly typed to a collection ofspecimensthat you will be able to loop through.This being said, personally I don’t like writing foreach loops in my views. They make them look ugly. In this case I would use a display template:
and then I would define a display template which will automatically be rendered for each element of the model collection (
~/Views/Shared/DisplayTemplates/specimen.ascx):See how the
specimen.ascxuser control is now strongly typed toSystem.Web.Mvc.ViewUserControl<WildlifeTropical.Models.specimen>. This is because it will be rendered for each specimen of the main view model.