你好,我正在尝试添加一个对象TempData
并重定向到另一个控制器操作。我在使用时收到错误消息 500TempData
.
public IActionResult Attach(long Id)
{
Story searchedStory=this.context.Stories.Find(Id);
if(searchedStory!=null)
{
TempData["tStory"]=searchedStory; //JsonConvert.SerializeObject(searchedStory) gets no error and passes
return RedirectToAction("Index","Location");
}
return View("Index");
}
public IActionResult Index(object _story)
{
Story story=TempData["tStory"] as Story;
if(story !=null)
{
List<Location> Locations = this.context.Locations.ToList();
ViewBag._story =JsonConvert.SerializeObject(story);
ViewBag.rstory=story;
return View(context.Locations);
}
return RedirectToAction("Index","Story");
}
P.S 阅读我添加的可能解决方案app.UseSession()
to the Configure
方法和services.AddServices()
in the ConfigureServices
方法但无济于事。有什么我必须注意的晦涩设置吗?
P.S添加ConfigureServices
and UseSession
配置服务
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddDbContext<TreasureContext>(x=>x.UseMySql(connectionString:Constrings[3]));
services.AddMvc();
services.AddSession();
}
配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
您必须先序列化对象,然后再将其分配给 TempData,因为核心仅支持字符串而不支持复杂对象。
TempData["UserData"] = JsonConvert.SerializeObject(searchedStory);
并通过反序列化来检索对象。
var story = JsonConvert.DeserializeObject<Story>(TempData["searchedStory"].ToString())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)