c# - 如何在返回 View 之前修改 Controller 中的查询字符串

标签 c# asp.net asp.net-mvc asp.net-mvc-4

有没有办法在返回 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/

相关文章:

c# - 更改 DatePicker 的边框颜色

c# - 哪一层做类似: caching and logging belong?的功能

c# - 授权属性中的角色在 MVC 4 中无法按预期工作

c# - <asp :Content> does not correspond with <asp:ContentPlaceholder>

c# - MVC6错误名称 'Configuration'在当前上下文中不存在

c# - 在 Razor 中使用一个提交按钮提交两个 HTML 表单

c# - 可选周围标签的优雅 MVC 代码

c# - CS0433 : The type 'List<T>' exists in both

c# - 在 .net 中的内存数据库中

jquery - 对隐藏字段执行验证