Marcel
Marcel

Reputation: 438

How to Invoke ViewComponents from View in ASP.NET MVC?

I am trying to Invoke Components from inside the view, but keep getting errors. And online I can only find examples working with ASP.NET Core, but I am not using Core.

This is my View:

@model BeestjeOpJeFeestje.Models.BoekingProces

<h2>Boeken</h2>
<hr />
<div class="row">
    <div class="col col-9" style="padding: 0">
        @switch (Model.Boeking.BoekingStatus)
        {
            case BeestjeOpJeFeestje.Models.BoekingStatus.Beestjes:
                if (TempData["error"] != null)
                {
                    <span class="text-danger">@TempData["error"]</span>
                }
                @await Component.InvokeAsync("BeestjesKiezen", @Model);
                break;
            case BeestjeOpJeFeestje.Models.BoekingStatus.Accessoires:
                @await Component.InvokeAsync("AccessoiresKiezen", @Model);
                break;
            case BeestjeOpJeFeestje.Models.BoekingStatus.Informatie:
                @await Component.InvokeAsync("Klantgegevens", @Model);
                break;
            case BeestjeOpJeFeestje.Models.BoekingStatus.Bevestiging:
                @await Component.InvokeAsync("Bevestiging", @Model);
                break;
        }
    </div>
    <div class="col col-3">
        @await Component.InvokeAsync("BookingDetail", @Model)
    </div>
</div>

But it results in the errors that 'await' and 'Component' not exists in the current context. enter image description here

Can someone maybe help me with the correct syntax? Thanks in advance.

Upvotes: 1

Views: 287

Answers (1)

Jerdine Sabio
Jerdine Sabio

Reputation: 6185

  1. This question has been answered before, the Component Static class is not available in ASP.NET MVC. It is only available with Core; Asp.net mvc compiler error when trying to invoke View Component from view page

  1. It is mentioned in the documentation that it is similar to a partial view, hence use that instead. But this won't have the asynchronous feature, the server will always wait for this rendering to finish before proceeding.
@{
    Html.RenderPartial("BeestjesKiezen", Model);
}

  1. Meanwhile, rendering parts of your page asynchronously can be done via ajax/jquery. See the answer here; How to render a partial view asynchronously

Upvotes: 1

Related Questions