gpt4 book ai didi

c# - 隐藏来自 ASP.NET MVC 中的操作的路由值?

转载 作者:行者123 更新时间:2023-11-30 23:19:13 29 4
gpt4 key购买 nike

我想根据请求来自的操作使用一个页面显示两个不同的文本,如果这个请求直接来自 Index,它会显示一些欢迎文本,如果它来自Create 表单显示一些其他文本:

public ActionResult Index(bool? ticketSent)
{
if (ticketSent == true)
ViewBag.IfcText = "done";
else
ViewBag.IfcText = "hello";
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TicketNumber,OwnerName,Email,LaptopModelNumber,Subject,Description,ComplainDate")] Ticket ticket)
{
if (ModelState.IsValid)
{
db.Tickets.Add(ticket);
db.SaveChanges();
return RedirectToAction("Index", new { ticketSent = true });
}

return View(ticket);
}

但是当请求来自 Create 操作时,Url 包含查询字符串 http://localhost:54401/?ticketSent=True,因此如果用户刷新浏览器,甚至在他获得指示表单已成功发送的同一页面时导航到它,我想确保在他仅创建没有查询字符串的表单后显示它。

这是 View :

@{if (ViewBag.IfcText == "hello")
{
<h2>Encountering a problem? We are here to help</h2>
<h3>
@Html.ActionLink("Contact our Support Team", "Create")
</h3>
}
else if (ViewBag.IfcText == "done")
{
@:<h2>We received it, we will be in contact with you in 24 hrs.</h2>
}
}

最佳答案

使用 TempData 来存储标志。它只会在上一个请求的重定向中可用,这正是您想要的。

查看这篇文章以获得更好的理解

When to use ViewBag, ViewData, or TempData in ASP.NET MVC 3 applications

这个概念仍然适用于最近版本的 MVC

const string ticketSentKey = "ticketSent";

public ActionResult Index()
{
var ticketSent = false;

if(TempData.ContainsKey(ticketSentKey) && TempData[ticketSentKey] is bool)
ticketSent = (bool)TempData[ticketSentKey];

if (ticketSent == true)
ViewBag.IfcText = "done";
else
ViewBag.IfcText = "hello";
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TicketNumber,OwnerName,Email,LaptopModelNumber,Subject,Description,ComplainDate")] Ticket ticket)
{
if (ModelState.IsValid)
{
db.Tickets.Add(ticket);
db.SaveChanges();
TempData[ticketSentKey] = true;
return RedirectToAction("Index");
}

return View(ticket);
}

关于c# - 隐藏来自 ASP.NET MVC 中的操作的路由值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40406127/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com