2013-04-11 35 views
6

我有一個網格中的鏈接我AdminUsers查看RedirecttoAction錯誤消息

grid.Column(header: "", format: (item) => (condition ? Html.ActionLink("Impersonate", "Impersonate", "Admin", new { id = item.username }, null) : Html.Label("Impersonate"), style: "webgrid-column-link"), 

在控制器中,我有

public ActionResult Impersonate(string id) 
{ 
    string result = ORCA.utilities.users.setImpersonation(id); 
    if(result == "nocommonfields") 
     return RedirectToAction("AdminUsers", "Admin"); 
    else 
     return RedirectToAction("terms_of_use", "Forms"); 
} 

如何發送一個錯誤信息,當我回到顯示AdminUsers頁面?

回答

23

您可以使用TempData的

if(result == "nocommonfields") 
{ 
    TempData["ErrorMessage"]="This is the message"; 
    return RedirectToAction("AdminUsers", "Admin"); 
} 

,並在您AdminUsers動作,你可以閱讀

public ActionResult AdminUsers() 
{ 
    var errMsg=TempData["ErrorMessage"] as string; 
//check errMsg value do whatever you want now as needed 
} 

記住,TempData的具有非常短的壽命。會話是臨時數據背後的備份存儲。

或者,您也可以考慮在您的查詢字符串中發送一個標誌,並在您的下一個操作方法中讀取它並確定要顯示的錯誤消息。

+0

是有可能恢復默認使用tempdata驗證錯誤並在ValidationMessageFor元素中顯示錯誤? – 2016-04-11 06:45:57

2

TempData控制器屬性可用於實現此類功能。我認爲它的主要缺點是它使用會話存儲來存儲它的內容。這意味着您需要額外的工作才能使其在Web場上運行,或者您需要首先打開會話。

關於TempData的好處是,這正是你想要的。它是一個基於字符串的字典,你可以放入任何東西,默認情況下它只會出來一次。所以在撥打RedirectToAction()之前,你要設置你的信息。在下一個請求中,您檢查消息並顯示它們。通過檢索消息,它們在請求結束時自動刪除。

作爲替代方案,您可以使用cookie在兩個請求之間傳輸消息。本質上,您可以推出自己的解決方案,或者實施通過cookie傳輸TempData的內容的自定義ITempDataProvider。請注意,您需要妥善保護cookie。 MachineKey.Protect()可以幫助你,如果你正在滾動你自己的。

我正面臨同樣的問題,併爲它創建了一個解決方案,稱爲FlashMessage。也許這可以爲你節省一些工作。它也可以在NuGet上找到。用法很簡單:你只需排隊一個消息調用RedirectToAction()之前如下:

if(result == "nocommonfields") 
{ 
    FlashMessage.Warning("Your error message"); 
    return RedirectToAction("AdminUsers", "Admin"); 
} 

在你看來,你包括以下語句,以使任何先前排隊的消息:

@Html.RenderFlashMessages() 
+0

好的解決方案,另一種可能性是發送querystring(當然,如果它不是一個敏感的數據)..雖然如果它是一個敏感的數據,我再次不確定將它存儲在cookie中(甚至用machineKey加密)即使我討厭使用它,這種想法也會導致我使用TempData :)但是,您的擴展名是FlashMESSAGE,我想這並不意味着將信用卡號存儲在cookie中 – sotn 2017-01-16 14:46:32