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

前端 未结 4 480
渐次进展
渐次进展 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-11-30 23:48

    I ran into a similar problem with the same error message using following code:

    @Html.DisplayFor(model => model.EndDate.Value.ToShortDateString())
    

    I found a good answer here

    Turns out you can decorate the property in your model with a displayformat then apply a dataformatstring.

    Be sure to import the following lib into your model:

    using System.ComponentModel.DataAnnotations;
    
    0 讨论(0)
  • 2020-11-30 23:56

    I had the same problem with something like

    @foreach (var item in Model)
    {
        @Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
    }
    

    I solved this just by doing

    @foreach (var item in Model)
    {
        var active = !item.IsIdle;
        @Html.DisplayFor(m => active , "BoolIcon")
    }
    

    When you know the trick, it's simple.

    The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.

    0 讨论(0)
  • 2020-12-01 00:04

    Fill in the service layer with the model and then send it to the view. For example: ViewItem=ModelItem.ToString().Substring(0,100);

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题