2017-08-07 184 views
1

之前是否有返回视图之前修改为ASP.NET MVC 4控制器的请求的查询字符串/ URL参数的方法吗?我想追加一个参数到URL。如何修改查询字符串返回控制器查看

我试着给Request.QueryString字典添加一个密钥,但它似乎是只读的。


其他背景信息:

我有一个ASP.NET MVC 4页,用户可以创建日历视图中的事件。当用户点击“创建事件”按钮时,系统会为该事件创建一个挂起的预留。用户然后被重定向到“编辑事件”视图。实际的日历事件是在用户填写“编辑事件”页面并提交时在未决预约上创建的。

我的问题是,我不想在每次加载“编辑事件”页面(例如使用F5刷新)时创建新的挂起预留。因此,我提出了将新创建的挂起预留Id添加到查询字符串的想法。这样每个连续的页面加载将使用现有的挂起预留。

但是,它似乎并不能够编辑控制器中的查询字符串。有没有其他方法可以做到这一点?

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

还有关于整体功能的任何建议,赞赏。

回答

1

您应该使用Post/Redirect/Get模式,以避免重复/多次提交表单。

喜欢的东西

[HttpPost] 
public ActionResult CreateEvent(CreateEventViewModelSomething model) 
{ 
    // some event reservation/persistent logic 
    var newlyReservedEventId = _calendarService.CreatePendingReservation(); 
    return return RedirectToAction("EditEvent", new { id = newlyReservedEventId }); 
} 

public ActionResult EditEvent(int id) 
{ 
    var model = new CalendarEventEditModel(); 
    model.PendingReservationId = id; 
    return View(model); 
} 
+0

谢谢。我意识到我的问题的根源是我正在创建GET请求上的资源。通过分离POST和GET请求,您的答案帮助我解决了这个问题。 – Koja

1

查询字符串是什么浏览器会将您。你不能在服务器上修改它;它已经发送。

相反,重定向到相同的路线,包括新创建的查询字符串。

0

使用此:

return this.RedirectToAction 
    ("EditEvent", model, new { value1 = "queryStringValue1" }); 

将返回:

/controller/EditEvent?value1=queryStringValue1 
相关问题