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 ?
Passing the data from Controller to View using TempData To pass the strongly typed data from Controller to View using TempData, we have to make a model class then populate its properties with some data and then pass that data to TempData as Value and selecting Key's name is the programmer's choice.
TempData is a property in the ControllerBase class. So, it is available in any controller or view in the ASP.NET MVC application. The following example shows how to transfer data from one action method to another using TempData.
This article will illustrate how to create a TempData object, store some data and then access the TempData object inside the View using Razor syntax in ASP.Net MVC Razor. In the below example, a string value is set in the TempData object in Controller and it is then displayed in View.
You can use Keep() when prevent/hold the value depends on additional logic. when you read TempData one's and want to hold for another request then use keep method, so TempData can available for next request as above example.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With