2016-11-03 37 views
2

我想用一个页面来显示基于请求来自的动作的两个不同文本,如果这个请求直接来自Index它显示一些欢迎文本,并且如果它来自Create窗体,它显示一些其他文本:在ASP.NET MVC中隐藏来自动作的路由值?

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,因此,如果用户刷新浏览器,甚至导航到它,他得到了相同的网页,随时指示形式发送成功,我想确保在创建表单时不显示查询字符串而显示它。

这是视图:

@{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> 
    } 
} 
+0

阅读本http://rachelappel.com/when-to -use-viewbag-viewdata-tempdata-in-asp-net-mvc-3-applications/ – Nkosi

+0

使用tempdata来存储标志。 – Nkosi

回答

2
使用

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); 
}