Home > Net >  Blazor component in MVC view: onclick event not working
Blazor component in MVC view: onclick event not working

Time:12-02

I am working on incorporating Blazor components into an MVC app in Visual Studio 2019. I have an MVC Razor View, Index.cshtml, which incorporates a blazor component UserIndex.razor, containing an onclick event. To test the onclick event there is a simple function in the UserIndex.razor's BaseComponent class UserIndexBase.cs, which changes the display value of a button across the top of the page. The component renders fine, and Intellisense works fine in the blazor component files, however the event either does not fire or or fails to complete its task successfully. (I am using the Firefox browser) There are some warnings and errors in the console log which I have included in the image below the code snippets. I have checked other questions on the blazor onclick event not working, but none seem to have a solution that applies to my case.

UserIndexBase.cs:

public class UserIndexBase : ComponentBase
{
    [Inject]
    public IUserAccountService UserAccountService { get; set; }

    [Parameter]
    public string Search { get; set; }

    public string Error { get; set; }

    [Parameter]
    public Listing<Account, AccountParams> Listing { get; set; }

    [Parameter]
    public Account UserToView { get; set; }

    public Account UserToEdit { get; set; }

    public Account UserToDelete { get; set; }

    [Parameter]
    public string Action { get; set; }

    [Parameter]
    public string Controller { get; set; }

    [Parameter]
    public Dictionary<string, object> RouteDataDict { get; set; }

    public async Task HandleSearchSubmit()
    {
        var searchFields = new string[] { "UserName", "Email" };
        var listingParams = new AccountParams
        {
            Search = Search,
            SearchFields = searchFields
        };
        var result = UserAccountService.GetListing(listingParams);
        if (result.Status != OpStatus.Ok)
        {

            return;
        }
        Listing = result.Listing;
        
    }

    public async Task ViewUser()
    {
        UserToView = new Account
        {
            Id = $"{Guid.NewGuid()}"
        };

        //var UserToView = UserAccountService.GetUser(userId);
    }
}

UserIndex.razor with the button on top containing the onclick trigger:

@inherits UserIndexBase
<button @onclick="ViewUser">@UserToView?.FirstName user</button>
<div class="content">
    <div class="page-content">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body p-35">
                        <div class="col-md-12 m-text-center">
                            <h1>Users</h1>
                            <small class="text-muted f-w-500">@Listing.Params.TotalDataSize users</small>
                        </div>
                        <div class="row m-b-10">
                            <div class="col-md-6">
                                <form action="@LinkGenerator.GetPathByAction("Index", "Users")" method="GET">
                                    <label class="tiny-label">&nbsp;</label>
                                    <div class="form-group">
                                        <div class="input-group mb-3">
                                            <input autocomplete="off" name="Search" type="text" class="form-control f-sz-1-em" placeholder="Search by username or email" aria-describedby="basic-addon2" value="@Search" />
                                            <div class="input-group-append">
                                                <button type="submit" id="search-btn" class="btn btn-secondary btn-icon p-t-6 p-b-6">
                                                    <i class="zmdi zmdi-search color-theme hover-color-white f-sz-1-em"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <input type="hidden" name="SearchFields[]" value="UserName" />
                                        <input type="hidden" name="SearchFields[]" value="Email" />
                                    </div>
                                </form>
                            </div>
                        </div>
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th scope="col">Name</th>
                                    <th scope="col">Username</th>
                                    <th scope="col">Email</th>
                                    <th scope="col">Contact</th>
                                    <th scope="col">Email</th>
                                    <th scope="col">Two Factor Enabled</th>
                                    <th scope="col">Created On</th>
                                    <th scope="col">Last Logged On</th>
                                    <th scope="col"></th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var user in Listing.Data)
                                {
                                    <tr>
                                        <td>@($"{user.FirstName} {user.LastName}")</td>
                                        <td>@user.UserName</td>
                                        <td>@user.Email</td>
                                        <td>@user.PhoneNumber</td>
                                        <td>@user.Email</td>
                                        <td>@(user.TwoFactorEnabled?"Yes":"No")</td>
                                        <td>@user.CreatedOn.ToString(Formats.DISPLAY_DATE_WITHOUT_DAY)</td>
                                        <td>
                                            @(user.LastLoggedOn==null?"":
                                        user.LastLoggedOn.Value.ToString(Formats.DISPLAY_DATE_WITHOUT_DAY))
                                        </td>
                                        <td>
                                            <button title="Actions" class="btn btn-tranparent btn-circle dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                <i class="zmdi zmdi-menu"></i>
                                            </button>
                                            <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                                <a class="dropdown-item" @onclick="ViewUser">View</a>
                                                <a class="dropdown-item" href="">Edit</a>
                                                <a class="dropdown-item" href="">Delete</a>
                                                <a class="dropdown-item" href="@(LinkGenerator.GetPathByAction("Index", "Profiles", new {UserId=user.Id}))">View Profiles</a>
                                            </div>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                        @if (Listing.Data.Count() > 0)
                        {
                            var pagingParams = PagingParams.GetPagingParams(Listing.Params);
                            <IndexPaging PagingParams="@pagingParams" Action="@Action" Controller="@Controller" RouteDataDict="@RouteDataDict" />
                        }
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

This is how the component is added to the Index.cshtml:

<component type="typeof(UserIndex)" render-mode="ServerPrerendered"
           param-Listing= "Model" param-Search = "search" param-Action= "action" param-Controller= "controller" param-RouteDataDict= "routeData" />

I have this in the tag of the _Layout.cshtml:

<base href="~/" />

And this at the bottom of the of _Layout.cshtml:

...
<script src="_framework/blazor.server.js"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>

This is my _Imports.razor:

@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using System.IO
@using System.Net.Http
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using System.IO

The following lines added in the appropriate places in Startup.cs:

services.AddServerSideBlazor();

....

app.UseEndpoints(endpoints => {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapBlazorHub();
            });

Portion of console log in browser

CodePudding user response:

The issue was a script pace.js script included. Not sure why, but when I excluded it the error stopped occuring.

  • Related