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

浪子不回头ぞ 提交于 2019-11-30 08:34:58

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

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()
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!