MVC and Entity Framework Html.DisplayNameFor with Composite ViewModel

后端 未结 2 483
一生所求
一生所求 2021-01-01 16:35

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

2条回答
  •  不思量自难忘°
    2021-01-01 16:45

    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 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();}
    
                    
            @Html.DisplayNameFor(model => headerMetadata.Abbreviation)
        
        
            @Html.DisplayNameFor(model => headerMetadata.DisplayName)
        
        ...
    

    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.

提交回复
热议问题