17

I fill my TempData from a FormCollection and then I try to check the value of my TempData in my view with MVC 4 but my if statement isn't working as I expect. Here is my code.

Controller :

[HttpPost]
public ActionResult TestForm(FormCollection data) 
{
    TempData["username"] = data["var"].ToString(); //data["var"] == "abcd"
    return RedirectToAction("Index");
}

View:

@if (TempData["var"] == "abcd") 
{
    <span>Check</span> //Never displayed
}
else
{
    @TempData["var"]; // Display "abcd"
}

This looks like really simple and I don't understand why I can't display this Check. Can you help me ?

Alex M
  • 2,410
  • 1
  • 24
  • 37
Alex
  • 2,927
  • 8
  • 37
  • 56
  • know **how to use** `TempData` properly check [this](http://sampathloku.blogspot.com/2012/09/how-to-use-aspnet-mvc-tempdata-properly.html) – Shaiju T Jul 02 '15 at 14:15

3 Answers3

22

Please try this

var tempval = TempData["var"];

then write your if statement as follow

@if (tempval.ToString() == "abcd") 
{
    <span>Check</span> //Never displayed
}
else
{
    <span>@tempval</span>; // Display "abcd"
}
Elvin Mammadov
  • 25,329
  • 11
  • 40
  • 82
  • I tried and I have the same result. `@tempval` gives me the good value but `if(@tempval == "myvalue") ` doesn't return true. – Alex Jul 25 '13 at 12:29
6

Try change TempData.Add("var", "abcd");

to

TempData['var'] = "abcd";

Update:

In My controller:

public ActionResult Index()
    {
        TempData["var"] = "abcd";
        return View();
    }

In my view:

// I cast to string to make sure it's checking for the correct TempData (string)
@if ((string)TempData["var"] == "abcd")
{
   <span>Check</span>
}
else
{
   @TempData["var"].ToString()
}
Lars
  • 589
  • 2
  • 13
  • 25
  • See my updated answer on how simply this should really work. If this not helps you, I would need some more info/code to help you out. – Lars Jul 25 '13 at 14:01
  • Thanks Lars. It was a problems troubling me for some time now how I couldn't do a conditional on a TempData value. Turns out it's an object! I am free at last! – JustJohn Mar 19 '16 at 23:22
0

Before starting any block of code in MVC View always start using @{ } then write any line of code and terminate with semicolon(;)

enter image description here

Ishwor Khanal
  • 1,312
  • 18
  • 30