Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 755
Alex Avatar asked Jul 25 '13 12:07

Alex


People also ask

How do I get TempData values in view?

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.

Can we access TempData in view?

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.

Can we pass TempData from controller to view?

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.

How do I use TempData keep 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.


1 Answers

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"
}
like image 172
Elvin Mammadov Avatar answered Nov 02 '22 13:11

Elvin Mammadov