Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a problem in code related to print Purchases's Report between two Period. I get an error: @item.products.ProductName always null

An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Reports_reportPurchaseDate.<executeasync>b__13_0() in reportPurchaseDate.cshtml, line 76

Stack Query Cookies Headers Routing
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Reports_reportPurchaseDate.<executeasync>b__13_0() in reportPurchaseDate.cshtml
+
@item.products.ProductName


What I have tried:

my Controller

C#
public class ReportsController : Controller    
{
    private MyDbContext _Context;

    public ReportsController(MyDbContext Context)
    {
        _Context = Context;
    }

    protected override void Dispose(bool disposing)
    {
        _Context.Dispose();
    }

    public bool getRole()
    {
        bool role = false;
        string group_id = HttpContext.Session.GetString("group_id");
        string username = HttpContext.Session.GetString("username");
        string Page_Current = HttpContext.Request.Path;
        var db = _Context.Permission_pages.Where(c => c.group_id.ToString() == group_id && c.page_name ==            
Page_Current).Select(p => p.page_name).ToList();

        if (db.Count != 0)
        {
            role = true;
        }
        else
        {
            role = false;
        }

        return role;
    }    

    public ActionResult reportPurchaseDate(DateTime datefrom, DateTime    dateto)
    {
        bool isrole = getRole();

        if (isrole == true)
        {
            var rpt = _Context.orderDetails.Where(c => c.masterID.Order_Kind_ID == 1 && c.masterID.DateAdded >= datefrom &&
c.masterID.DateAdded <= dateto)
                .Include(c => c.masterID)
                .Include(c => c.products.ProductName)
                .ToList();

            return View(rpt);
        }
        else
        {
            return RedirectToAction("noaccess", "HomeController");
        }
    }
}



my View

C#
@model IEnumerable<orderdetails>
@{    
     ViewData["Title"] = "report purchase Date";    
     Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1> Report Purchase</h1>

    
    <table class="table"><tbody><tr>        <td>            
        </td>        <td>            Date From
        </td>    </tr>    <tr>        <td>            @Html.TextBox("dateto")
        </td>        <td>           Date To
        </td>    </tr>    <tr>        <td>            
        </td>        <td>        </td>    </tr>    </tbody></table>    <hr>
        <hr>    <div class="row">
    <div class="col-md-12">
        <div class="content-panel">
            <h4>
                class="fa fa-angle-right">
                Report Purchase
            </h4>
            <hr>
            
                                    @foreach (var item in Model)
                    {
                                            }

                <table class="table"><thead>                    <tr>                        <td>                           Product Name
                        </td>                        <td>                          Price
                        </td>                        <td>                           Quantity
                        </td>                        <td>                           Date
                        </td>                    </tr>                </thead>                <tbody><tr>                            <td>                                @item.products.ProductName

                            </td>                            <td>                                @item.Product_Price
                            </td>                            <td>                                @item.Product_Quantity
                            </td>                            <td>                                    @Html.DisplayFor(modelItem => item.masterID.DateAdded)
                                </td>                        </tr></tbody>            </table>
        </div>
    </div>
    </div>
    
    @section Scripts
    {    
        
        function PrintElem(elem) {
            Popup($(elem).html());
        }

        function Popup(data) {
            var myWindow = window.open('', 'my div', 'height=500,width=600');
            myWindow.document.write('<html><head><title>my div</title>');
            myWindow.document.write('<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" type="text/css" />');
            myWindow.document.write('</head><body >');
            myWindow.document.write(data);
            myWindow.document.write('</body></html>');
            myWindow.document.close(); // necessary for IE >= 10

            myWindow.onload = function () { // necessary if the div contain images

                myWindow.focus(); // necessary for IE >= 10
                myWindow.print();
                myWindow.close();
            };
        }    
        
    }
Posted
Updated 23-Jun-20 20:40pm
v2
Comments
F-ES Sitecore 24-Jun-20 1:38am    
If ProductName is null then there is either an issue with how your tables relate or the data in them. We have access to neither so can't really help. Use SQL Profiler to find out exactly what SQL your code is executing and go from there.

I put some HTML comments in your block of code which should get you going in the right direction...
Spoonboy would say "There is no 'item' ", at least not at that point in the code. It only existed within the (empty) foreach loop
HTML
<div class="row">
   <div class="col-md-12">
      <div class="content-panel">
         <h4>class="fa fa-angle-right">Report Purchase</h4>
         <hr>
         @foreach (var item in Model) {
            <!-- nothing in this loop -->
         }
         <table class="table">
            <thead>
               <tr>
                  <td>   Product Name</td>
                  <td>  Price</td>
                  <td>   Quantity</td>
                  <td>   Date</td>
               </tr>
            </thead>
            <tbody>
               <tr>
                  <td>@item.products.ProductName</td> <!-- what is "item" ? -->
                  <td>@item.Product_Price</td>
                  <td>@item.Product_Quantity</td>
                  <td>@Html.DisplayFor(modelItem => item.masterID.DateAdded)</td>
               </tr>
            </tbody>
         </table>
      </div>
   </div>
</div>
 
Share this answer
 
v2
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 

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