Click here to Skip to main content
15,892,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 24:     </tr>
Line 25: 
Line 26:     @foreach (var item in @Model)
Line 27:     {
Line 28:         using (Html.BeginForm("Delete", "Employee", new { id = item.Id }))

Source File: E:\Visual Studio 2019\Kuduvenkat MVC\BusinessLayer_Model2\BusinessLayer_Model2\Views\Employee\Index.cshtml    Line: 26


What I have tried:

@model IEnumerable<BusinessLayer.Emp>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Salary)
        </th>
        <th></th>
    </tr>

    @foreach (var item in @Model)
    {
        using (Html.BeginForm("Delete", "Employee", new { id = item.Id }))
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Gender)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Salary)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |

                    <input type="submit" value="Delete" onclick="return confirm('Are you sure want to delete this record with Name = @item.Name')"/>

            </tr>
        }
    }
</table>
Posted
Updated 5-Feb-20 8:35am
v2

1 solution

What that error means is that Model being called in line 26 is null; therefore it does not have items.

Generally I wrap these in an if...then block.. you should be able to drop this into your view relatively easily
C#
if ((Model == null) || (Model.Count < 1)) {
	/* display message explaining no records found */
} else {
	foreach (var item in Model) {
		/* display records */
	}
}
 
Share this answer
 
Comments
Gauravg9598 6-Feb-20 8:11am    
Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900