Tempdata["Message"] error in Runtime saying the object is null

Asked

Viewed 831 times

3

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

Object Reference not set to an instance of an Object

I’ve done a lot of research, and anyway, from what I’ve been told, they just told me that Tempdata is null because it’s null instead of:

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

was

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

I’ve seen some answers that didn’t clarify very well, I even used one NullReferenceException(); launching this excpetion after Else, but another programmer Elsewhere he replied that it would not be advisable for me to use it like this. How can I fix this mistake?

This image below is of 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>**
  • Hi, Raffa, welcome to [en.so]. I got your question formatted, it’s better use Markdown HTML when publishing here. I was in a doubt, the code contains these ** or you tried to make Bold on it?

  • Hello, thank you, I don’t think I misplaced these ** !

  • Okay, it’s my ignorance of language then ;)

  • I don’t understand ???

  • No, no problem, I found it strange, but if it’s normal everything is ok. I didn’t touch it when editing because I wasn’t sure, I just wanted to confirm. Good luck!

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 collection’s "Message" key TempData;
  • 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 cannot be converted to string.

A possible solution is the following:

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

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

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

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 because 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.

  • Can you explain why your code solves the problem? Check out the guide [Answer] for more details.

  • 1

    What these mean ("<b>sucess.</b>") can you give me more details, please !

  • this Success was just an example of how your program could proceed if there was value within Tempdata.

1

I managed to fix my own mistake. The code is like this now, compared to the top, that put 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 misses error or success. In this case, I believe that this message must come from a BLL because I’m with the project part branch here and not the trunk the original so I can’t see where the original message comes from. In @if the comparison that is now right, the one that was before, was wrong because I was comparing the tempData 2 times, and so returned me the error:

Object Reference not set to an instance of an Object

in the old comparison was so:

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 made this mistake Object reference not set to an instance of an object me launched a Exception wrong way, I used this: NullReferenceException but it was not advisable to use since it would only work from the time of the Runtime, anyway this Excpetion wouldn’t solve my problem. The comparison of which mensagem is or what is going on whether wrong or not, it already does in the @if. What I really wanted was img.png more was playing 2 times to @Html.Raw and the tempData Once again after Isis 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 that the @Html.Raw only needed to pass once, and the comparison would come in the same image, but how ? using QueryString Each Controller has its ActionResult, in this case some of the actions in Controllers used JsonResult I’m going to illustrate with a project code here for you to understand, I’m going to show you a JsonResult within a Controller, then you still have the file JS in the briefcase Scripts, look at this one 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 });
    }

They watch, there in the bool return if true it will save the message, as I said the message must be coming from a BLL, but I can’t see it here, because I don’t have the original project code, just one copy code, so you can move on to the original and go up in production. He checks in the ClienteBLL.CadastrarCliente() whether it was successful or not, whatever it is, it will store the message in the timeData["Message"], and will return this message to me by:

4

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

Forget this RedirectUrl only in the Retorno

But you still have the Archive JS how will he still know which is the View which should display this message ? here it is:

5

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

A few photos for you to see, look at the folder Views of Base Controllers and in a View Message

inserir a descrição da imagem aqui

Another photo to look at, look at BaseController.cs and just below the Views, Base, Mensagem

inserir a descrição da imagem aqui

Where Base is the name of the folder of a Controller and Mensagem is the name of View which she shall display, and using Query String ?retorno=' + json.Retorno from where ? remember ? this json.Return comes from:

6

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

Look over there Retorno = retorno where this variable retorno comes gives (variable bool return = Clientebll.Signup client() look at the part 3:

7 Code of View Message

<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 hope that my doubt I had and that I get, and along with the other reply posts here, help others with similar doubts, hug

Browser other questions tagged

You are not signed in. Login or sign up in order to post.