1

i'm new in Asp Net and i have some questions. So i make an example to understand, this example return a tempData with the match name in the List. The List has 3 objects created in the actionResult Index.

   [HttpPost]
    public ActionResult Buscar(String NomeP)
    {
        int i;
        List<Models.Produto> Lista = null;

        Lista = Session["SSLista"] != null ? (Session["SSLista"] as List<Models.Produto>) : new List<Models.Produto>();
        for (i = 0; i< Lista.Count; i++) {
            if (Lista[i].Nome.Equals(NomeP)) {
                TempData["Found"] = Lista[i];
            }
        }
      return RedirectToAction("Produto", "Home");

}

When i try to show the return i receive this exception of NUllReference, but the tempData has some data in return.

<% Html.EndForm(); %> <%

if (TempData["Found"] != null)
{ %>
<% 
foreach (var prod in (TempData["Found"] as List<MvcApplication2.Models.Produto>))
{
%>
<br />
<h2>Produtos</h2>
<label>
   Nome: <%=prod.Nome %>
</label>
 <label>
   Descrição <%= prod.Descricao%>
</label>
 <label>
   Preço: <%= prod.Valor_unitario%>
</label>
 <label>
   ID: <%= prod.Id%>
</label><br>
<% }
}

The image below show's that Tempdata has some Data, but i can convert in the foreach.

  • 1
    No idea why you have accepted a wrong answer that has nothing to do with your problem. In your controller, `TempData["Found"] = Lista[i];` is adding a single `Produto` to TempData (not a collection). Then in the view you try and cast a single `Produto` to `List` which of course fails and its `null` –  Apr 09 '16 at 23:16

2 Answers2

2

You should be able to find the null which causes the NullReferenceException value by simply debugging your code. And you should also state which view are you trying to access it.

But in the current situation you are setting the individual instances of Models.Produto to TempData["Found"] but casting it to List<MvcApplication2.Models.Produto> which results a null reference.

Try setting TempData["Found"] = Lista; in the controller.

0

TempData : Is generally used to pass data between one Action method to another, if you want to pass data from controller to view, use ViewBag or ViewData.


Anyways the problem is you are assigning just Models.Produto to your TempData

 TempData["Found"] = Lista[i];

After the for loop the TempData just has the last iterated item in it, And in your view you are trying to cast to List<Models.Produto>

foreach (var prod in (TempData["Found"] as List<MvcApplication2.Models.Produto>))

Which is the problem.

Try this

 [HttpPost]
    public ActionResult Buscar(String NomeP)
    {
        int i;
        List<Models.Produto> Lista = null;
        List<Models.Produto> TempList = new  List<Models.Produto>(); //new variable

        Lista = Session["SSLista"] != null ? (Session["SSLista"] as List<Models.Produto>) : new List<Models.Produto>();
        for (i = 0; i< Lista.Count; i++) {
            if (Lista[i].Nome.Equals(NomeP)) {
                TempList.Add(Lista[i]); // add the items to the temp list
            }
        }

      TempData["Found"] = TempList; //assign the final list to temp data
      return RedirectToAction("Produto", "Home");
}

Also I found this out after yildizm85 pointed it out. So all credits to him. I updated my answer to avoid further down votes.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
  • So, if i use the ViewData, i can get the Data in the View ? but make in this way i have to modify the return to View. Like this ? Return View(); – Mathias Cruz Apr 09 '16 at 18:40
  • Yes, But I see you are redirecting to another Action which in-turn redirects to your view right? So first you need to access the Tempdata in your `Produto` Action and then assign it again to a ViewBag. Here go the section where it explains about TempData http://www.codeproject.com/Articles/476967/WhatplusisplusViewData-cplusViewBagplusandplusTem – Rajshekar Reddy Apr 09 '16 at 18:43
  • I modify and add a viewData in the action Produto, i receive the data in the view correctly. But in the foreach convert i still have the exception. foreach (var prod in (ViewData["Found"] as List)). Thanks for the help – Mathias Cruz Apr 09 '16 at 18:57
  • @Reddy I'm afraid 'TempData' does quite to opposite according to the article. It holds the content in redirects. –  Apr 09 '16 at 19:03
  • @yildizm85 taken from the article, `TempData keeps the information for the time of an HTTP Request. This mean only from one page to another. This also works with a 302/303 redirection because it’s in the same HTTP Request. It helps to maintain data when you move from one controller to other controller or from one action to other action. ` – Rajshekar Reddy Apr 09 '16 at 19:09
  • @MathiasCruz I updated my answer – Rajshekar Reddy Apr 09 '16 at 23:31
  • 1
    Don't you think yildizm85 at least deserves an up-vote. –  Apr 10 '16 at 07:48
  • @StephenMuecke upvoted :) – Rajshekar Reddy Apr 11 '16 at 07:23