Using TempData dictionary prevents RedirectToAction from working

孤街醉人 提交于 2019-12-06 14:18:13

It is not much of an answer, but I experienced the same issue with no resolution. I changed tempdata to a Session["rvm"] variable and was successful. Consider pivoting from tempdata to Session.

This is by design. In Asp.Net core, you cannot pass complex types in TempData. You can pass simple types like string, int, Guid etc.

If you absolutely want to pass a complex type object via TempData, you have 2 options.

1) Serialize your object to a string and pass that.

Here is a sample using Json.NET to serialize the object to a string

var s = Newtonsoft.Json.JsonConvert.SerializeObject(rvm);
TempData["rvm"] = s;
return RedirectToAction("About", "Home");

Now in your About action method, read this value from the TempData and deserialize it to your RegisterViewModel class object.

public IActionResult About()
{
   if (TempData["rvm"] is string s)
   {
       var rvm = JsonConvert.DeserializeObject<RegisterViewModel>(s);
       // use rvm now
   }
   // to do : return something
}

2) Set a dictionary of simple types to TempData

var d = new Dictionary<string, string>
{
    ["FullName"] = rvm.FullName,
    ["Email"] = rvm.Email;
};
TempData["MyModelDict"] = d;
return RedirectToAction("About", "Home");

and read it later

public IActionResult About()
{
   if (TempData["MyModelDict"] is Dictionary<string,string> dict)
   {
      var name = dict["Name"];
      var email =  dict["Email"];
   }
   // to do : return something
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!