Mohamed Ahmed Mohamed Ahmed - 1 month ago 8
C# Question

Hide routing values coming from action in ASP.NET MVC?

I want to use one page for showing two different texts based on the action the request coming from, if this request comes directly from the

Index
it shows some welcome text, and if it comes from the
Create
form it shows some other text:

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


but when the request comes from the
Create
action the Url contains the query string,
http://localhost:54401/?ticketSent=True
, thus if the user refreshed the browser or even navigate to it any time he gets the same page indicating that the form sent successfully, I want to ensure it's being shown after he creates the form only without the query string.

This is the 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>
}
}

Answer

use TempData to store the flag. It will only be available on the redirect from the previous request, which is what you wanted.

Check out this article to get a better understanding

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

The concept still applies for recent versions of 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);
}