“Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions” error

前端 未结 4 483
渐次进展
渐次进展 2020-11-30 23:11

Why am I receiving the error:

Templates can be used only with field access, property access, single-dimension array index, or single-parameter cus

4条回答
  •  死守一世寂寞
    2020-12-01 00:05

    The template it is referring to is the Html helper DisplayFor.

    DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.

    You are trying to pass in a method chain to be executed and it doesn't like it.

    This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.

    You could wrap up your Trainer model class in another class called TrainerViewModel that could work something like this:

    class TrainerViewModel
    {
        private Trainer _trainer;
    
        public string ShortDescription
        {
            get
            {
                return _trainer.Description.ToString().Substring(0, 100);
            }
        }
    
        public TrainerViewModel(Trainer trainer)
        {
            _trainer = trainer;
        }
    }
    

    You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.

    Then you would modify your controller to return a TrainerViewModel object rather than a Trainer object and change your model type declaration in your view file to TrainerViewModel too.

提交回复
热议问题