Click here to Skip to main content
14,356,706 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi I'm getting a scary problem The controller is invoked normally, the foreach loop works fine, call the view with a List return and the @foreach start the loop and load the registers brought from the DB, but in the last interaction it brokes.


Server Error in Application '/'. Object reference not set to an instance of an object.enter image description here Exception Details: System.NullReferenceException: Object reference not defined for an instance of an object.


---> View








@model IEnumerable<VitrineVirtual.Model.Carrinho_Compras>



<div class="ibox-content">
	<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="15">
		<tbody>
			@foreach (var item in Model.Where(item => item != null))
			{
				<tr>
					<td>
						<div class="product-detail">
							<ul>
								<li><span>@Html.DisplayFor(modelItem => item.Nome_Produto)</span></li>
								<li><span>@Html.DisplayFor(modelItem => item.Modelo_Produto)</span></li>
								<li><span>@Html.DisplayFor(modelItem => item.Descricao_Produto)</span></li>
							</ul>
						</div>
					</td>


What I have tried:

I tried to do with viewdata, viewbag, IEnumerable, List, IList every possibilities but nothing. Is somebody have any spirit and glourious solution? Thanks a lot. The variable names it´s in portuguese, but I keeped the main names like dbcontext in ingles or the standar initials.
Posted
Updated 29-Aug-19 9:10am
Rate this:
Please Sign up or sign in to vote.

Solution 1

You need to debug your code and find out which property is set to NULL. That is something nobody can do for you, as we don't have any access to your data. By last "interaction" I guess you meant iteration - so I suspect the last item in Model have some property set to NULL while you trying to use it. I think this may actually happen in the part of the code you haven't posted.

Also, the thrown exception should have a stack trace which tell you in what line the error occurs.
   
Comments
Member 12132704 30-Aug-19 9:04am
   
jimmson, the decimal properties was the problems, I declare like nullable class in the model so Nullable<decimal> and set some properties like MadMyche suggest and works fine.
Rate this:
Please Sign up or sign in to vote.

Solution 2

There is no "one solution" - 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!
   
Rate this:
Please Sign up or sign in to vote.

Solution 3

A couple of possibilities here
1. The Model being passed in is NULL
2. One of the properties of the Model.Item is NULL

For the first case scenario, what I do is specifically check before I try to iterate through it
@if (Model != null) {
   foreach (var item in Model.Where(item => item != null)) {
For the second scenario, you can use NULL Coalescing and Conditionals when calling the particular property
Member access operators - C# reference | Microsoft Docs[^]
Expressions - C# language specification | Microsoft Docs[^]

The way I handle this is via a static class for Extension Methods, which has routines for all of the data types that I use
using System {
   public static partial class PublicExtensions {
      public static string ForcedString(this object NullableObject, string DefaultValue = "") {
         return (NullableObject == null ? DefaultValue : NullableObject.ToString().Trim());
      }
And for your scenario it would be plumbed in like this
<span>@Html.DisplayFor(modelItem => item.Nome_Produto.ForcedString())</span>
   
Comments
Member 12132704 30-Aug-19 9:00am
   
MadMyche your snnipet code works fine for me
The problem was solved I took tasks:
First I include a static class named ForcedString to treat nullable properties.
Second I setted to Nullable class all the decimal attributes in this model and the foreach interate yill the last and call the view normally.
Thanks for all sugestions.
MadMyche 30-Aug-19 16:31pm
   
You're welcome
Rate this:
Please Sign up or sign in to vote.

Solution 5

Probably that it must be a property setted as null, why the Model isn't null for sure, I checked debugging and the List<> has data.

I'm using decimal properties and its not Nullable declared, it could be a problem?

In Controller a do like this:
var items = db.CarrinhoCompras.Where(x => x.ID_Usuario == idUsuario).ToList();
if (items != null)
{
ViewData["Qtd_Items"] = items.Count;
ViewData["Package"] = items;
decimal total = 0;
total = items.Select(x => x.Price).Sum();
ViewData["Total"] = total;
ViewData["Total_Order"] = 1;
}

return View(items);


In View

<tbody>
                        @foreach (var item in Model.Where(item => item != null))
                        {
                            <tr>
                                <td width="120">
                                    <div class="cart-product-imitation">
                                        <a href="#" title="Foto">
                                            <img style="position:initial" width="90" height="90" src="@Url.Content(item.Caminho_Arquivo.ForcedString())" />
                                        </a>
                                    </div>
                                </td>
                                <td>
                                    <div class="product-detail">
                                        <ul>
                                            <li><span>@Html.DisplayFor(modelItem => item.Nome_Produto)</span></li>
                                            <li><span>@Html.DisplayFor(modelItem => item.Modelo_Produto)</span></li>
                                            <li><span>@Html.DisplayFor(modelItem => item.Descricao_Produto)</span></li>
                                        </ul>
                                    </div>
                                </td>
                                <td>
                                    <div class="product-price">
                                        @Html.DisplayFor(modelItem => item.Preco_Produto)
                                        <input type="text" id="txtAtualizaPreco" name="preco" class="form-control">
                                        <input type="hidden" name="preco" id="hdnAtualizaPreco" value="@item.Preco_Produto.ForcedString()" />
                                    </div>
                                </td>
                                <td width="40">
                                    <div class="btn-group">
                                        <button id="btnExcuiItemcarrinho" class="btn-danger btn btn-xs apaga" value="Excuir"></button>
                                        <input type="hidden" name="itemCarrinho" id="hdnExcluiItemCarrinho" value="@item.ID_Carrinho_Compras.ForcedString()" />
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="hidden-phone bg-dark">
                                    <input type="button" id="btnAtualizaPreco" value="Calcular" class="form-control text-white" style="background-color: #3872a2">
                                </td>
                            </tr>
                        }
                    </tbody>
   

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100