有没有办法在返回 View 之前修改 ASP.NET MVC 4 Controller 中请求的查询字符串/URL 参数?我想向 URL 附加一个参数。
我尝试在 Request.QueryString
字典中添加一个键,但它似乎是只读的。
附加上下文信息:
我有一个 ASP.NET MVC 4 页面,用户可以在其中在日历 View 中创建事件。当用户单击“创建事件”按钮时,系统会为该事件创建一个挂起的预订。然后将用户重定向到“编辑事件” View 。当用户填写“编辑事件”页面并提交时,实际的日历事件将在待处理的预订上创建。
我的问题是我不想在每次加载“编辑事件”页面(例如使用 F5 刷新)时都创建一个新的待定预订。因此,我想出了将新创建的待处理预订 ID 添加到查询字符串的想法。这样,每次连续的页面加载都将使用现有的待处理预留。
但是,似乎无法在 Controller 中编辑查询字符串。有替代方法吗?
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);
}
也欢迎任何有关整体功能的建议。
最佳答案
你应该使用 Post/Redirect/Get避免重复/多次提交表单的模式。
像这样:
[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);
}
关于c# - 如何在返回 View 之前修改 Controller 中的查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45544434/