I’m fairly comfortable with MVVM using WPF/Silverlight but this is my first attempt at an MVC Web Application…just an fyi for my background.
I’ve created a controlle
I finally figured this out after messing around for several hours.
1st problem in order to use the Display arrtibute in the Data Anotations a get and set acessor methods must be added even if they are only the default ones. I'm assuming this is because they must only work on properties and not public data members of a class. Here is code to get the
@Html.DisplayNameFor(model => model.WebPageTitle)
to work correctly
public class TestSitesViewModel
{
//Eventually this will be added to a base ViewModel to get rid of
//the ViewBag dependencies
[Display(Name = "Web Page Title")]
public string WebPageTitle { get; set; }
//PUBLIC DATA MEMBER WON'T WORK
//IT NEEDS TO BE PROPERTY AS DECLARED ABOVE
//public string WebPageTitle;
public IEnumerable<MVCWeb.MyEntities.Site> Sites;
//Other Entities, IEnumberables, or properties go here
//Not important for this example
}
2nd part of problem was accessing the Metadata in an IEnumerable variable. I declared temporary variable called headerMetadata and used it instead of trying to access the properties through the IEnumerable
@{var headerMetadata = Model.Sites.FirstOrDefault();}
<tr>
<th>
@Html.DisplayNameFor(model => headerMetadata.Abbreviation)
</th>
<th>
@Html.DisplayNameFor(model => headerMetadata.DisplayName)
</th>
...
This does beg the question of when does headerMetadata variable go out of scope? Is it available for the entire view or is it limited to the html table tags? I suppose that's another question for another date.
I'll take a stab with my newly learned MVVM ASP.NET MVC experience.
Instead of calling @Html.DisplayNameFor(model => model.WebPageTitle)
, try using @Html.DisplayFor(model => model.WebPageTitle)
. You appear to be setting the WebPageTitle value in your IndexWithViewModel controller which should show up in your view.
Look into shared templates for ASP.NET MVC. You can set up custom templates or partials for DisplayFor/EditorFor helpers at /Views/Shared/EditorTemplates/Site.cshtml
and /Views/Shared/DisplayTemplates/Site.cshtml
. ASP.NET MVC will automatically pick up on those templates when rendering your Site object with DisplayFor and EditorFor.
Good luck!