[英]How to modify query string in Controller before returning View
有沒有辦法在返回視圖之前修改 ASP.NET MVC 4 控制器中請求的查詢字符串/URL 參數? 我想在 URL 中附加一個參數。
我嘗試向Request.QueryString
字典添加一個鍵,但它似乎是只讀的。
附加上下文信息:
我有一個 ASP.NET MVC 4 頁面,用戶可以在其中在日歷視圖中創建事件。 當用戶單擊“創建事件”按鈕時,系統會為該事件創建一個掛起的預訂。 然后將用戶重定向到“編輯事件”視圖。 當用戶填寫“編輯事件”頁面並提交時,實際的日歷事件會在未決預訂上創建。
我的問題是,我不想在每次加載“編輯事件”頁面(例如,使用 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);
}
查詢字符串是瀏覽器發送給您的內容。 你不能在服務器上修改它; 它已經發送了。
相反,重定向到相同的路由,包括新創建的查詢字符串。
用這個:
return this.RedirectToAction
("EditEvent", model, new { value1 = "queryStringValue1" });
將返回:
/controller/EditEvent?value1=queryStringValue1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.