in the layout.cshtml. In a method of my controller, I set TempData["pipo"] = "xyz"; and " /> in the layout.cshtml. In a method of my controller, I set TempData["pipo"] = "xyz"; and " /> in the layout.cshtml. In a method of my controller, I set TempData["pipo"] = "xyz"; and "/>

ASP.NET Core MVC model binding does not work with TempData

258 views Asked by At

I have an <input type="hidden" id="pipo" name="pipo" value /> in the layout.cshtml.

In a method of my controller, I set TempData["pipo"] = "xyz"; and then return RedirectToAction(nameof(aView));.

When aView is rendered, the input "pipo" has "xyz" as value.

But when in another method, I set TempData["pipo"] = "xyz" but in place of a return RedirectionToAction I have a return View("aView"), the pipo input does not have a value.

I tried making a

return RedirectToAction("aView") 

in place of

return View("aView")

in that case the input have a value "xyz". Maybe I lost something in the way that values from TempData goes to an <input> or maybe there is something that RedirectToAction does that View() does not.

Temporarily, I'm doing 2 loads, with a RedirectToAction when I need it, but there should be a way to not doing that.

2

There are 2 answers

1
Maddy On

Temp data can be used to set a property. But how are you expecting that value to set the ? send your input value to your controller method values and then from that value assign it your tempdata variable.

Like:

public ActionResult BatchPapers(string pipo)
{
  if(pipo != null)
      {
     TempData["pipo"] = pipo; 
      }
  else{
     TempData["pipo"] = "xyz" 
      }
}
4
Qiang Fu On

Tried to retrive your scenario:

        public IActionResult aView()
        {
            TempData["pipo"] = "xyz";

            return View();
        }
        public IActionResult Method1()
        {
            return View("aView");
        }

        public IActionResult Method2()
        {
            
            return RedirectToAction("aView");
        }
<input id="pipo" name="pipo" value=@TempData["pipo"] />

Go Method1 won't change value to xyz. But Method2 could do the change.
This is because return view("aView") won't make a new request, it just go directly to the aView.cshtml.
But return RedirectToAction("aView") will make a new request to aview method first, so it changed the value.
Difference Between return View(), return Redirect(), return RedirectToAction()