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

3

18

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 ?

Bryson answered 25/7, 2013 at 12:1 Comment(1)
know how to use TempData properly check thisService
E
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"
}
Effeminate answered 25/7, 2013 at 12:10 Comment(1)
I tried and I have the same result. @tempval gives me the good value but if(@tempval == "myvalue") doesn't return true.Bryson
C
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()
}
Crass answered 25/7, 2013 at 12:12 Comment(2)
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.Crass
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!Luci
D
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

Determinism answered 30/8, 2018 at 6:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.