IT story

"템플릿은 필드 액세스, 속성 액세스, 단일 차원 배열 인덱스 또는 단일 매개 변수 사용자 지정 인덱서 식에만 사용할 수 있습니다."오류

hot-time 2020. 9. 7. 21:23
반응형

"템플릿은 필드 액세스, 속성 액세스, 단일 차원 배열 인덱스 또는 단일 매개 변수 사용자 지정 인덱서 식에만 사용할 수 있습니다."오류


오류가 발생하는 이유 :

템플릿은 필드 액세스, 속성 액세스, 단일 차원 배열 인덱스 또는 단일 매개 변수 사용자 지정 인덱서 식에만 사용할 수 있습니다.

이 코드에서 :

@model IEnumerable<ArtSchoolProject.Models.Trainer>

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_PageLayout.cshtml";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<ul class="trainers">


@foreach (var item in Model) {
<li>
  <div>
      <div class="left">
          <a href="@Url.Action("Details", "Details", new { id = item.ID })">
              <img src="~/Images/Trainer/@item.Picture" />
          </a>
      </div>
      <div class="right">
          @Html.ActionLink(item.Name,"Details",new {id=item.ID})
          <br />
          @Html.DisplayFor(modelItem=>@string. item.Description.ToString().Substring(0,100))
      </div>
  </div>
  </li>
  }

  </ul>

줄에서 :

@Html.DisplayFor(modelItem=>item.Description.ToString().Substring(0,100))

최신 정보:

문제 해결됨. 내 코드에 추가했습니다.

  @{
string parameterValue = item.Description.ToString().Substring(0, 100); 
          }
          @Html.DisplayFor(modelItem=>parameterValue)

내 새 코드 :

@foreach (var item in Model) {
<li>
  <div>
      <div class="left">
          <a href="@Url.Action("Details", "Details", new { id = item.ID })">
              <img src="~/Images/Trainer/@item.Picture" />
          </a>
      </div>
      <div class="right">
          @Html.ActionLink(item.Name,"Details",new {id=item.ID})
          <br />
          @{
string parameterValue = item.Description.ToString().Substring(0, 100); 
          }
          @Html.DisplayFor(modelItem=>parameterValue)
      </div>
  </div>
 </li>
}

이것은 하나의 가능성입니다. 호기심을 위해 오류를 해결하는 또 다른 해결책이 있습니까?


나는 같은 문제가 있었다.

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

나는 이것을함으로써 이것을 해결했다.

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

트릭을 알면 간단합니다.

차이점은 첫 번째 경우에는 메서드를 매개 변수로 전달한 반면 두 번째 경우에는 식이라는 것입니다.


참조하는 템플릿은 Html 도우미 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.


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;

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

참고URL : https://stackoverflow.com/questions/21754071/templates-can-be-used-only-with-field-access-property-access-single-dimension

반응형