TempData ["Message"] error in the runtime saying that the object is null

3

I recently started with ASP.NET MVC, and as you can see I'm playing in the if statement, else the tempData[] and the one that happens is a following, every time I click inside the else in "View in Page Inspector" it gives me an error in the window, it is the same error at the time of Debug, I only use this option "View in Page Inspector" Visual Studio does not have to wait to run and so on. In this "View in Page Inspector" it shows me right in the next window without having to run the code, showing me if it will work or not. It returns me this message:

  

Object reference not set to an instance of an object

I have already researched a lot and finally, for what they answered, they only told me that TempData is nullo, since it is instead of:

TempData["Mensagem"].ToString() != ""

was

TempData["Mensagem"].ToString() != null

I have already seen some answers that did not clarify very well, I even used a NullReferenceException(); throwing this excpetion after the else, but another programmer Elsewhere he told me that I should not use it like that. How can I resolve this error?

This image below is from my open project:

**<!--MAIN-->
    <div class="main">

        <section class="container">
            <a onclick="javascript:FecharPopup()" href="@Ecommerce.Code.UrlMaker.UrlHome()" class="FecharPopup"></a>

                <article class="linha1">
                    <h1>
                        @if (TempData["Mensagem"].ToString() != "")
                        {
                            @Html.Raw(TempData["Mensagem"].ToString());
                            <figure><img src="/Content/Images/Mensagem/erro.png" alt=""/></figure>
                        }
                        else
                        {
                            //throw new ArgumentNullException();
                            @Html.Raw(TempData["Mensagem"].ToString());
                            <figure><img src="/Content/Images/Mensagem/sucess.png" alt=""/></figure>   
                        }
                    </h1>
                </article>

            <article class="linha2">
                <p>Em caso de dúvidas, <a target="_parent" href="@Ecommerce.Code.UrlMaker.UrlCentralAtendimento()">fale conosco.</a></p>
            </article>

        </section>
    </div>**
    
asked by anonymous 02.09.2014 / 17:09

3 answers

3

Let's look at the following line from the compiler's point of view:

TempData["Mensagem"].ToString() != ""

It translates as follows:

  • Get the value of the indexed property relative to the "Message" key of the TempData collection;
  • Convert this value to string ;
  • Tell me if the converted value is different from an empty string ("").

The problem lies between the first and second steps. The value returned from the TempData collection is null, and null can not be converted to string.

One possible solution is as follows:

(TempData["Mensagem"] ?? "").ToString() != ""

?? is the agglutination operator ( coalesce operator ). The sequence now works as follows:

  • Get the value of the indexed property relative to the "Message" key of the TempData collection;
  • If the value is null, assume that the value is an empty string ("").
  • Convert this value to string ;
  • Tell me if the converted value is different from an empty string ("").
02.09.2014 / 17:30
2

Try:

**<!--MAIN-->
    <div class="main">

        <section class="container">
            <a onclick="javascript:FecharPopup()" href="@Ecommerce.Code.UrlMaker.UrlHome()" class="FecharPopup"></a>

                <article class="linha1">
                    <h1>
                        @if (TempData["Mensagem"] != null)
                        {
                            @Html.Raw(TempData["Mensagem"].ToString());
                            <figure><img src="/Content/Images/Mensagem/erro.png" alt=""/></figure>
                        }
                        else
                        {
                            @Html.Raw("<b>Sucesso.</b>");
                            <figure><img src="/Content/Images/Mensagem/sucess.png" alt=""/></figure>   
                        }
                    </h1>
                </article>

            <article class="linha2">
                <p>Em caso de dúvidas, <a target="_parent" href="@Ecommerce.Code.UrlMaker.UrlCentralAtendimento()">fale conosco.</a></p>
            </article>

        </section>
    </div>**

This can solve why you check if it has any value before trying to convert it to string .. what you were doing is converting nothing to string and this generated the error.

    
02.09.2014 / 17:16
1

I managed to resolve my own mistake. The code is so now, compared to the one above, put it before! What I really wanted was to bring the message that was coming from TempData["Mensagem"] and make a comparison, to be able to identify if the message errs of error or of success. In case, I believe this message should come from a BLL because I'm with the part of the project branch here and not the trunk the original so I can not see where the original message comes from. In%% of the comparison that is now right, the one that was previously, was wrong because I was comparing tempData 2 times, and for this I returned the error:

  

Object reference not set to an instance of an object

In the old comparison it looked like this:

  

1:

   @if (TempData["Mensagem"].ToString() != "")
               {
               @Html.Raw(TempData["Mensagem"].ToString());
               <figure><img src="/Content/Images/Mensagem/erro.png" alt=""/></figure>
               }
               else
               {
               //throw new ArgumentNullException();
               @Html.Raw(TempData["Mensagem"].ToString());
               <figure><img src="/Content/Images/Mensagem/sucess.png" alt=""/></figure>   
                }

See the difference? So much so that when I gave this error @if eu I did a Object reference not set to an instance of an object wrongly, I used this: Exception but it was not advisable to use it since it would only work at runtime, anyway that NullReferenceException would not solve my problem. The comparison of which Excpetion is or what is happening if wrong or not, it already does in mensagem . What I really really wanted was @if more was playing 2 times img.png and @Html.Raw again after else look:

  

2

   else
   {
   //throw new ArgumentNullException();
   @Html.Raw(TempData["Mensagem"].ToString());
   <figure><img src="/Content/Images/Mensagem/sucess.png" alt=""/></figure>   
   }

Playing and comparing twice being tempData only needed to pass once, and the comparison would come in the same image, but how? using @Html.Raw Every QueryString has its Controller , in this case some of the Actions in the ActionResult used Controllers I will exemplify with a project code here for you to understand, I will show a JsonResult within a JsonResult , later you still have the file Controller in the Scripts folder, look at this JsonResult :

  

3

    [HttpPost]
    public JsonResult CadastrarCliente(ClienteEntity cliente)
    {
        string mensagem = string.Empty;

        string url = url = Code.UrlMaker.UrlCentralCliente();

        bool retorno = ClienteBLL.CadastrarCliente(cliente, out mensagem);

        //Guarda a mensagem que será exibida
        TempData["Mensagem"] = mensagem;

        return Json(new { RedirectUrl = url, Retorno = retorno });
    }

Note that in the bool return if true it will save the message, as I said the message should be coming from a JS , but I can not see here, because I'm not with the original project code, just a copy code , to be able to go to the original and upload in production. It checks in BLL whether it was successful or not, whatever it is, it will save the message in tempData ["Message"], and will return this message to me:

  

4

 return Json(new { RedirectUrl = url, Retorno = retorno });

Forget this ClienteBLL.CadastrarCliente() only in RedirectUrl

But you still have the Retorno file as it will still know what JS should this message display? here it is:

  

5

    function RetornoPostCadastro(json) 
    {
    $.ExibirMensagem('/Base/Mensagem?retorno=' + json.Retorno, 400, 445);
    }

Some photos for you to see, look at the Views folder of View and inside a View Message

Anotherphototolookat,lookatBaseControllersandrightbelowBaseController.cs

Where Views, Base, Mensagem is the folder name of a Base and Controller is the name of the View that it will display , and using Query String Mensagem of where? Remember? this json. Return comes from:

  

6

   return Json(new { RedirectUrl = url, Retorno = retorno });

Look at%% of% where this ?retorno=' + json.Retorno variable is given variable bool return = ClientBLL.CountClient () look at part Retorno = retorno :

  

7 Message View Code

<div class="main">

    <section class="container">
   <a onclick="javascript:FecharPopup()" href="@Ecommerce.Code.UrlMaker.UrlHome()" class="FecharPopup"></a>

     <article class="linha1">
        <h1>
           @if (TempData["Mensagem"] != null && !string.IsNullOrEmpty(TempData["Mensagem"].ToString()))
                {
                 @Html.Raw(TempData["Mensagem"].ToString());
                 }
                 <figure>
                 @if (HttpContext.Current.Request.QueryString["retorno"] == "true")
                  {
                  <img src="/Content/Images/Mensagem/sucess.png" alt=""/>
                  }
                  else
                  {
                  <img src="/Content/Images/Mensagem/erro.png" alt=""/>    
                  }
                 </figure>
         </h1>
       </article>

       <article class="linha2">
         <p>Em caso de dúvidas, <a target="_parent" href="@Ecommerce.Code.UrlMaker.UrlCentralAtendimento()">fale conosco.</a></p>
       </article>

     </section>
   </div>
 <!--MAIN-->

That's it, thank you to those who answered and I hope that my doubt that I had and that I can, and along with the other response posts here, help others with similar questions, hug

>     
03.09.2014 / 16:30