Search code examples
blazorsyncfusionblazor-editformeditform

How to get the right context for the SfListView Template inside the EditForm Blazor component?


I have a SfListView inside the EditForm. In the Template section, at the line 'var fileItem = (context as AttachmentFile);' I receive the next error: CS0039 Cannot convert type 'Forms.EditContext' to 'Models.AttachmentFile' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion. A conversion with the as operator is allowed by inheritance, reference conversions, and boxing conversions.

Here is my code:

<EditForm EditContext="@myContext" OnSubmit="OnSendClick">
<SfListView EnableVirtualization="true" DataSource="@attachments">
    <ListViewFieldSettings TValue="AttachmentFile" Id="@nameof(AttachmentFile.Id)" Text="@nameof(AttachmentFile.Name)">
    </ListViewFieldSettings>
    
    <ListViewTemplates TValue="AttachmentFile">
        <Template>
            @{
                var fileItem = (context as AttachmentFile);

                <div class="rezmessage-attachment-file">
                    <i class="@fileItem.Icon"></i>
                    <a href="@fileItem.WebPath" target="_blank">fileItem.Name</a>
                </div>
            }
        </Template>
    </ListViewTemplates>
</SfListView>

How to get context that relates to the SfListView, not to EditForm?


Solution

  • You can define the scoped name for the context using the Context attribute Ms docs on the template elements.

    Then you won't even need to cast it (context as AttachmentFile);

    <EditForm EditContext="@myContext" OnSubmit="OnSendClick">
      <SfListView EnableVirtualization="true" DataSource="@attachments">
        <ListViewFieldSettings TValue="AttachmentFile" Id="@nameof(AttachmentFile.Id)" Text="@nameof(AttachmentFile.Name)">
        </ListViewFieldSettings>
    
        <ListViewTemplates TValue="AttachmentFile">
          <Template Context="templateContext">
            @{
              var fileItem = templateContext;
    
              <div class="rezmessage-attachment-file">
                <i class="@fileItem.Icon"></i>
                <a href="@fileItem.WebPath" target="_blank">@fileItem.Name</a>
              </div>
            }
          </Template>
        </ListViewTemplates>
      </SfListView>
    </EditForm>