2017-08-07 186 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 
相關問題