0

I created a search function to show the product name. But in my View it show the error at the foreach. I don't understand why it returns Object reference not set to an instance of an object.

Here's the error: enter image description here Here is my Controller:

public ActionResult _searchPartial()
    {
        List<tblProduct> getProduct = new List<tblProduct>();
        getProduct = db.tblProducts.ToList();
        return View("_searchPartial", getProduct);
    }

    [HttpPost]
    public ActionResult _searchPartial(string getProductName)
    {
        List<tblProduct> getProduct = new List<tblProduct>();
        getProduct = db.tblProducts.Where(m => m.ProductName.Contains(getProductName)).ToList();
        return View("_searchPartial", getProduct);
    }

the View:

@model  IEnumerable<JAx_Collections.Models.tblProduct>

<table style="text-align:center";>
        <tr>    
            <th>Product Name</th>
        </tr>
             @foreach (var m in Model)
             {
         <tr>
            <td>@m.ProductName</td>
         </tr>
             }
</table>

The Model:

namespace JAx_Collections.Models
{
    using System;
    using System.Collections.Generic;

    public partial class tblProduct
    {
        public int ProductID { get; set; }
        public int SupplierID { get; set; }
        public int CategoryID { get; set; }
        public string ProductName { get; set; }
        public int UnitPrice { get; set; }
        public int UnitsInStock { get; set; }
        public int UnitOnOrder { get; set; }

        public virtual tblCategory tblCategory { get; set; }
        public virtual tblSupplier tblSupplier { get; set; }
    }
}
progammer101
  • 47
  • 1
  • 8
  • A `foreach` is syntactic sugar for what essentially becomes a call to `GetEnumerator()`. Your `Model` is null in your GET. Have you tried setting a breakpoint on the `return View("_searchPartial", getProduct);` line in the GET action method to make sure `getProduct` is not null? You might think it won't be null because you've initialised it.. but literally the line after initialization youre setting its value to something else... which can be `null`. – Simon Whitehead Oct 21 '16 at 02:10
  • @SimonWhitehead how to set a breaking point? im just new in c# programming – progammer101 Oct 21 '16 at 02:32
  • 1
    You would do well to learn some basic debugging before jumping into an MVC project. It will save you lots of time. [Here is an MSDN article on how to use breakpoints](https://msdn.microsoft.com/en-us/library/5557y8b4.aspx). – Simon Whitehead Oct 21 '16 at 02:42

1 Answers1

1

This error also known as NRE (NullReferenceException), see What is a NullReferenceException, and how do I fix it?.

In your issue, the GET method from controller returns a list from database context (tblProducts), which potentially contains null value when no results provided. You can add an if-condition to check against null reference before returning view:

public ActionResult _searchPartial()
    {
        List<tblProduct> getProduct = new List<tblProduct>();
        getProduct = db.tblProducts.ToList();
        if (getProduct != null)
        {
            return View("_searchPartial", getProduct);
        }
        else
        {
            return View("_searchPartial"); // return without passing model
        }
    }

Also, in your view, use the same way to check presence of null on passed model:

@model  IEnumerable<JAx_Collections.Models.tblProduct>

<table style="text-align:center";>
        <tr>    
            <th>Product Name</th>
        </tr>
         @if (Model != null)
         {
             foreach (var m in Model)
             {
             <tr>
                <td>@m.ProductName</td>
             </tr>
             }
         }
</table>

Remember that any reference types should be check against null value before passing to any view, especially when collection iteration occurs on view side.

Community
  • 1
  • 1
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • 1
    `.ToList()` cannot return `null` - only an empty collection. It can only throw the exception if the source (`db.tblProducts`) is `null` (inaccessible) –  Oct 21 '16 at 06:10
  • IMHO, OP requires additional check by using `getProduct.Count > 0` in controller code to check if the collection has zero count. Also, if the null comes from inaccessible `tblProducts` context, the NRE break should pointed to `getProduct` assignment, not on `Model` inside view. – Tetsuya Yamamoto Oct 21 '16 at 06:23
  • 2
    It does not need that at all - if there are no items the `foreach` won't even be executed. And OP has not shown the relevant code (the code shown will not throw that exception). And next time, flag or vote to close as a dupe –  Oct 21 '16 at 06:25