Object reference not set to an instance of an object error when saving with CommandColumn in Grid

Hi,

I'm getting an "Object reference not set to an instance of an object." error passed via the 

OnActionFailure event when I use the save command column.

@page "/UserAccounts"

@using Syncfusion.Blazor.Navigations

@using Syncfusion.Blazor.Grids


<div class="container-fluid">

    <div class="vx-pagetitle" style="padding-bottom: 10px;">

        <span class="vx-icon-useraccounts"></span>

        <span id="pageTitle">@Glossary_UserAccounts</span>

    </div>


    <SfTab ID="RecentPinnedTab">

        <TabItems>

            <TabItem>

                <ChildContent>

                    <TabHeader Text="Accounts" IconCss="vx-icon-useraccounts"></TabHeader>

                </ChildContent>

                <ContentTemplate>

                @if (this.UserList != null)

                {

                    <SfGrid ID="UserAccounts" [email protected] AllowPaging="true" AllowSorting="true" AllowMultiSorting="true" AllowFiltering="true" AllowResizing="true" AllowTextWrap="true" @ref=@GridUserAccounts>

                        <GridEvents TValue=@UserModel CommandClicked=@GridOnCommandClicked OnActionBegin=@GridOnActionBegin OnActionFailure=@GridOnActionFailure></GridEvents>

                        <GridEditSettings AllowEditing="true" AllowDeleting="true"></GridEditSettings>

                        <GridPageSettings [email protected] PageSize=@PageSize></GridPageSettings>

                        <GridFilterSettings Type ="Syncfusion.Blazor.Grids.FilterType.Excel"></GridFilterSettings>

                        <GridTemplates>

                            <EmptyRecordTemplate>

                                <span>@RecordsText</span>

                            </EmptyRecordTemplate>

                        </GridTemplates>

                        <GridColumns>

                            <GridColumn HeaderText="User name" TextAlign="TextAlign.Left" IsPrimaryKey=@true Width="15%">

                                <Template>

                                    @{

                                        UserModel UserModelObj = (context as UserModel);

                                            <div><a rel='nofollow' href="#" @onclick=@(() => EditUser(@UserModelObj.Id)) @onclick:preventDefault>@UserModelObj.UserName</a></div>

                                    }

                                </Template>

                                <EditTemplate>

                                    @{

                                        UserModel UserModelObj = (context as UserModel);

                                            <div><a rel='nofollow' href="#" @onclick=@(() => EditUser(@UserModelObj.Id)) @onclick:preventDefault>@UserModelObj.UserName</a></div>

                                    }

                                </EditTemplate>

                            </GridColumn>

                            <GridColumn Field=@nameof(UserModel.FirstName) HeaderText="First name" TextAlign="TextAlign.Left" Width="15%"/>

                            <GridColumn Field=@nameof(UserModel.SecondName) HeaderText="Second name" TextAlign="TextAlign.Left" Width="15%"/>

                            <GridColumn Field=@nameof(UserModel.RoleId) HeaderText="Role" TextAlign="TextAlign.Left" Width="10%"/>

                            <GridColumn Field=@nameof(UserModel.Email) HeaderText="Email" TextAlign="TextAlign.Left" Width="15%"/>

                            <GridColumn HeaderText="Last Login" TextAlign="TextAlign.Center" Width="10%">

                                <Template>

                                    @{

                                        UserModel UserModelObj = (context as UserModel);

                                        string temp = string.Format(DateTimeFormat, UserModelObj.LastLogin);

                                        <div>@temp</div>

                                    }

                                </Template>

                                <EditTemplate>

                                    @{

                                        UserModel UserModelObj = (context as UserModel);

                                        string temp = string.Format(DateTimeFormat, UserModelObj.LastLogin);

                                        <div>@temp</div>

                                    }

                                </EditTemplate>

                            </GridColumn>

                            <GridColumn Field=@nameof(UserModel.Suspended) HeaderText="Suspended" TextAlign="TextAlign.Center" [email protected] DisplayAsCheckBox="true" Width="10%"/>

                            <GridColumn HeaderText="Edit accounts" TextAlign="TextAlign.Center" Width="10%">

                                <GridCommandColumns>

                                    <GridCommandColumn Type="CommandButtonType.Edit" ButtonOption="@(new CommandButtonOptions() { IconCss = "e-icons e-edit", CssClass = "e-flat" })"></GridCommandColumn>

                                    <GridCommandColumn Type="CommandButtonType.Delete" ButtonOption="@(new CommandButtonOptions() { IconCss = "e-icons e-delete", CssClass = "e-flat" })"></GridCommandColumn>

                                    <GridCommandColumn Type="CommandButtonType.Save" ButtonOption="@(new CommandButtonOptions() { IconCss = "e-icons e-update", CssClass = "e-flat" })"></GridCommandColumn>

                                    <GridCommandColumn Type="CommandButtonType.Cancel" ButtonOption="@(new CommandButtonOptions() { IconCss = "e-icons e-cancel-icon", CssClass = "e-flat" })"></GridCommandColumn>

                                </GridCommandColumns>

                             </GridColumn>

                        </GridColumns>

                    </SfGrid>

                }

                </ContentTemplate>

            </TabItem>

            <TabItem>

                <ChildContent>

                    <TabHeader Text="Groups" IconCss="vx-icon-useraccounts"></TabHeader>

                </ChildContent>

                <ContentTemplate>

                </ContentTemplate>

            </TabItem>

            <TabItem>

                <ChildContent>

                    <TabHeader Text="Roles" IconCss="vx-icon-useraccounts"></TabHeader>

                </ChildContent>

                <ContentTemplate>

                </ContentTemplate>

            </TabItem>

        </TabItems>

    </SfTab>

</div>



using Application.Interface;

using Microsoft.AspNetCore.Components;

using Microsoft.AspNetCore.Components.Authorization;

using Microsoft.AspNetCore.Identity;

using Models;

using ServiceData.Interface;

using Syncfusion.Blazor.FileManager;

using Syncfusion.Blazor.Grids;

using System.Diagnostics;

using Utility;


namespace Rosetta.Pages

{

    public partial class UserAccounts

    {

        #region Services

        [Inject]

        private ILogger<UserAccounts> Logger { get; set; } = null!;

        [Inject]

        private IGlossaryRepository GlossaryRepositoryObj { get; set; } = null!;

        [Inject]

        private IApplicationRepository ApplicationRepositoryObj { get; set; } = null!;

        [Inject]

        private IUserRepository UserRepositoryObj { get; set; } = null!;

        #endregion


        #region Cascading parameters

        [CascadingParameter]

        private Task<AuthenticationState> AuthenticationStateObj { get; set; } = null!;

        #endregion


        #region Declarations

        private SfGrid<UserModel> GridUserAccounts { get; set; } = null!;


        // User access

        private UserModel UserModelObj { get; set; } = null!;

        private List<UserModel> UserList { get; set; } = null!;


        private string Glossary_UserAccounts { get; set; } = string.Empty;

        private string DateTimeFormat { get; set; } = string.Empty;


        private int PageSize { get; set; } = GridConfiguration.PageSizeDefault;

        private string RecordsText { get; set; } = string.Empty;

        #endregion


        #region Life cycle events

        protected override async Task OnInitializedAsync()

        {

            // Get Logged on User

            AuthenticationState authState = await AuthenticationStateObj;

            this.UserModelObj = await UserRepositoryObj.GetUserByNameAsync(authState.User.Identity.Name);


            this.Glossary_UserAccounts = await GlossaryRepositoryObj.GetGlossaryTermAsync(GlossaryTermType.USERACCOUNTS);

            this.DateTimeFormat = await ApplicationRepositoryObj.GetStringAsync(ApplicationSettingType.DATETIMEFORMAT);


            // User Admin rights is all or nothing. Access is controlled through access to user menu

            this.UserList = await UserRepositoryObj.GetUsersSuspendedAsync();

            if (this.UserList.Count > 0)

                this.RecordsText = TString.value(GridConfiguration.LoadingText);

            else

                this.RecordsText = TString.value(GridConfiguration.NoRecordsText);

        }

        #endregion


        #region framework events

        public async Task GridOnCommandClicked(CommandClickEventArgs<UserModel> args)

        {

            //_state = await Grid.GetPersistData())

            //Grid.SetPersistData(_state))

            //Grid.ResetPersistData())

            //string state = await GridUserAccounts.GetPersistData();


            // Perform required operations here

        }

        public void GridOnActionBegin(ActionEventArgs<UserModel> Args)

        {


        }


        // Capture Grid errors

        private void GridOnActionFailure(Syncfusion.Blazor.Grids.FailureEventArgs args)

        {

            Logger.LogError(args.Error.Message);

            Debug.Assert(false);

        }

        #endregion


        private void EditUser(string UserId)

        {


        }

    }

}


 

using System;

using Microsoft.AspNetCore.Identity;


namespace Models

{

    // Mapped database class used by Identity/Dapper

    public class UserModel: IdentityUser

    {

        public string FirstName { get; set; }

        public string SecondName { get; set; }

        public string JobTitle { get; set; }

        public string RoleId { get; set; }

        public DateTime? LastLogin { get; set; }

        public bool Suspended { get; set; } = false;

        public bool Deleted { get; set; } = false;

        public override string ToString() => $"{this.FirstName} {this.SecondName} ({base.UserName})";

    }

}




4 Replies

MA Michael Aston June 23, 2022 07:47 AM UTC

Any feedback on this?



SP Sarveswaran Palani Syncfusion Team June 23, 2022 08:40 AM UTC

Hi Michael,


Sorry for the delay & inconvenience caused 


We have analyzed your query and having issue when run your attached code snippet. So, using OnActionFailure event, we replicated your sample of command column grid based on your requirement . But we are unable to reproduce any exception as you mentioned. Kindly refer the attached sample for your reference. If you are facing the same problem again, please reproduce the reported problem in the provided sample.


Kindly get back to us if you have any further queries.


Regards,

Sarveswaran PK


Attachment: GridCommandColumn_602761ad.zip


MA Michael Aston June 23, 2022 12:27 PM UTC

Thanks for the sample it helped me find the issue. If you are using commandcolumns and you are using a template on the column marked as primary then you still need to associate the field to the model.


           <GridColumn Field=@nameof(UserModel.UserName) HeaderText="User name" TextAlign="TextAlign.Left" IsPrimaryKey=@true Width="15%">

                <Template>

                    @{

                        UserModel UserModelObj = (context as UserModel);

                            <div><a rel='nofollow' href="#" @onclick=@(() => EditUser(@UserModelObj)) @onclick:preventDefault>@UserModelObj.UserName</a></div>

                    }

                </Template>

                <EditTemplate>

                    @{

                        UserModel UserModelObj = (context as UserModel);

                            <div>@UserModelObj.UserName</div>

                    }

                </EditTemplate>

            </GridColumn>



SP Sarveswaran Palani Syncfusion Team June 24, 2022 06:51 PM UTC

Hi Michael,


Thanks for contacting Syncfusion support.


We have analyzed your query and modified the sample by applying template to primary key column. But we could not able to replicate the issue.


Kindly refer the attached sample and if you are still facing an issue, please share video demo of the issue you are facing.


Regards,

Sarveswaran PK


Attachment: GridCommandColumn(1)_fca62fd5.zip

Loader.
Up arrow icon