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

后端 未结 3 768
闹比i
闹比i 2020-12-31 04:27

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 is

相关标签:
3条回答
  • 2020-12-31 05:04

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

    0 讨论(0)
  • 2020-12-31 05:06

    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"
    }
    
    0 讨论(0)
  • 2020-12-31 05:11

    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()
    }
    
    0 讨论(0)
提交回复
热议问题