将重定向消息传递到ASP.NET MVC中的视图
我有一个ASP.NET MVC在线商店式应用程序,具有两个视图:将重定向消息传递到ASP.NET MVC中的视图,asp.net,asp.net-mvc,redirect,Asp.net,Asp.net Mvc,Redirect,我有一个ASP.NET MVC在线商店式应用程序,具有两个视图: 项目页面(照片、描述等) 用户可以留下评论的表单 用户成功提交表单后,应将其重定向回项目页面,并在顶部显示一条一次性消息:“您的审核已成功提交” 控制器代码(简化)如下所示: [HttpGet] public ActionResult ViewItem([Bind] long id) { var item = _context.Items.First(x => x.Id == id); return Vi
- 项目页面(照片、描述等)
- 用户可以留下评论的表单
[HttpGet]
public ActionResult ViewItem([Bind] long id)
{
var item = _context.Items.First(x => x.Id == id);
return View(item);
}
[HttpGet]
public ActionResult AddReview()
{
return View();
}
[HttpPost]
public ActionResult AddReview([Bind] long id, [Bind] string text)
{
_context.Reviews.Add(new Review { Id = id, Text = text });
_context.SaveChanges();
return RedirectToAction("ViewItem");
}
有几个要求需要满足:
- 如果用户刷新项目的页面,则该消息不得再次显示
- 邮件不得污染URL
- 控制器方法不能合并为一个
我曾考虑将消息存储在用户会话中,并在显示后将其丢弃,但可能有更好的解决方案吗?通过使用tempdata可以将消息或数据(字符串/对象)从一个页面传递到另一个页面,并且它仅在一个操作到另一个操作时有效 有关tempdata的一些要点:
[HttpPost]
public ActionResult AddReview([Bind] long id, [Bind] string text)
{
_context.Reviews.Add(new Review { Id = id, Text = text });
_context.SaveChanges();
TempData["message"] = "someMessage";
return RedirectToAction("ViewItem");
}
在您的查看页面中:
@TempData["message"]; //TempData["message"].ToString();
ViewBag或ViewData会比Session更好。请参阅此处推荐的TEMPDATA,它将充当flash messenger。@Andy,该博客没有解释为什么它“更好”(你的评论也没有),该博客只是从markpsmith链接的问答中复制出来的。和。