Is there a way to modify the query string/URL parameters for a request in ASP.NET MVC 4 Controller before returning the view? I want to append a parameter to the URL.
I tried adding a key to the Request.QueryString dictionary, but it seems to be read-only.
Additional context information:
I have an ASP.NET MVC 4 page where the user can create an event in a calendar view. When the user clicks the "Create event" button, the system creates a pending reservation for the event. The user is then redirected to an "Edit event" view. The actual calendar event is created over the pending reservation when the user has filled the "Edit event" page and submits.
My problem is that I don't want to create a new pending reservation every time the "Edit event" page is loaded (e.g. refreshing with F5). Thus, I came up with the idea to add the newly-created pending reservation Id to the query string. This way every consecutive page-load will use the existing pending reservation.
However, it doesn't seem to be possible to edit the query string in the Controller. Is there an alternative way to do this?
public ActionResult CreateEvent()
{
var model = new CalendarEventEditModel();
//This should be true for the first time, but false for any consecutive requests
if (Request.QueryString["pendingReservationId"] == null)
{
model.PendingReservationId = _calendarService.CreatePendingReservation();
//The following line throws an exception because QueryString is read-only
Request.QueryString["pendingReservationId"] = model.PendingReservationId.ToString();
}
return View("EditEvent", model);
}
Also any suggestions regarding the overall functionality are appreciated.
You should use Post/Redirect/Get pattern to avoid duplicate/multiple form submission.
Something like this:
[HttpPost]
public ActionResult CreateEvent(CreateEventViewModelSomething model)
{
// some event reservation/persistent logic
var newlyReservedEventId = _calendarService.CreatePendingReservation();
return RedirectToAction("EditEvent", new { id = newlyReservedEventId });
}
public ActionResult EditEvent(int id)
{
var model = new CalendarEventEditModel();
model.PendingReservationId = id;
return View(model);
}
The query string is what the browser sends you. You can't modify it on the server; it's already been sent.
Instead, redirect to the same route, including the newly created query string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With