0

I want to go back from the Create Page to the Index Page which is in the Database and it still does not have any data.
This is the code in index page:

@if (Model.Books.Count() > 0 )
    {
        <table class="table table-bordered table-striped">
            <tr class="table-secondary">
                <th>
                    <label asp-for="Books.FirstOrDefault().Name"></label>
                </th>
                <th>
                    @Html.DisplayNameFor(a => a.Books.FirstOrDefault().Author)
                </th>
                <th>
                    <label asp-for="Books.FirstOrDefault().ISBN"></label>
                </th>
                <th>

                </th>
            </tr>
            @foreach (var data in Model.Books)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(a => data.Name)
                    </td>
                    <td>
                        @Html.DisplayFor(a => data.Author)
                    </td>
                    <td>
                        @*using html helper to display the data*@
                        @Html.DisplayFor(a=>data.ISBN)
                    </td>
                    <td>
                        <button class="btn btn-success btn-sm">Edit</button>
                        <button class="btn btn-danger btn-sm">Delete</button>
                    </td>
                </tr>
            }
        </table>
    }
    else
    {
        <p class="text-center text-danger">No Book Available.<br /><b>Please create a book !!</b></p>
    }

When it is directly from Home to the Index Page it will go to the else statement , but from Create Page to the Index , an error is occurred.

I would like to know how to handle this exception or this error ?
I think it is not practical to develop without any dummy data but just for knowledge.
Is there any idea ?

LopDev
  • 823
  • 10
  • 26
Whys24
  • 11
  • 1
  • You must check for @if (Model !=null && Model.Books.Count() > 0 ) so when navigating from other pages if model is not filled these following set of code doesn't run. – Hammad Sajid Oct 05 '20 at 08:10
  • if Books is null, Model.Books.Count() will throw exception. use Model?.Books?.Count() to void throw exception – J. Hsu Oct 05 '20 at 08:19
  • Thanks @J.Hsu the code works, i note that – Whys24 Oct 05 '20 at 08:45

1 Answers1

3

Your first if statement gives null reference exception when the model is null or Model.Books is null.

change @if (Model.Books.Count() > 0 ) to

 @if (Model?.Books?.Count() > 0 )
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72