How to check TempData value in my view after a form post?

Alex picture Alex · Jul 25, 2013 · Viewed 71.9k times · Source

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 ?

Answer

Elvin Mammadov picture Elvin Mammadov · Jul 25, 2013

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"
}