Asp.net-Mvc
ASP.NET MVC ViewData if 語句
我在我的視圖中使用以下內容來檢查是否存在類似 domain.com/?query=moo 的查詢
if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code }但是現在需要更改它,以便它檢查 ViewData 查詢是否存在而不是查詢字元串,但不太確定如何重寫它。我的 ViewData 看起來像這樣:
ViewData["query"]任何人都可以幫忙嗎?謝謝
if (ViewData["query"] != null) { // your code }如果你絕對必須得到一個字元串值,你可以這樣做:
string query = (ViewData["query"] ?? string.Empty) as string; if (!string.IsNullOrEmpty(query)) { // your code }
用鍍金擴展亨特的答案……
這
ViewDataDictionary是光榮的無類型。檢查值是否存在的最簡單方法(Hunter 的第一個範例)是:
if (ViewData.ContainsKey("query")) { // your code }您可以使用 [1] 之類的包裝器:
public static class ViewDataExtensions { public static T ItemCastOrDefault<T>(this ViewDataDictionary that, string key) { var value = that[key]; if (value == null) return default(T); else return (T)value; } }這使人們可以將亨特的第二個例子表達為:
String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))但總的來說,我喜歡將此類檢查包裝在顯示命名擴展方法的意圖中,例如:
public static class ViewDataQueryExtensions { const string Key = "query"; public static bool IncludesQuery(this ViewDataDictionary that) { return that.ContainsKey("query"); } public static string Query(this ViewDataDictionary that) { return that.ItemCastOrDefault<string>(Key) ?? string.Empty; } }這使得:
@if(ViewData.IncludesQuery()) {…
var q = ViewData.Query(); }應用此技術的更詳細的範例:
public static class ViewDataDevExpressExtensions { const string Key = "IncludeDexExpressScriptMountainOnPage"; public static bool IndicatesDevExpressScriptsShouldBeIncludedOnThisPage(this ViewDataDictionary that) { return that.ItemCastOrDefault<bool>(Key); } public static void VerifyActionIncludedDevExpressScripts(this ViewDataDictionary that) { if (!that.IndicatesDevExpressScriptsShouldBeIncludedOnThisPage()) throw new InvalidOperationException("Actions relying on this View need to trigger scripts being rendered earlier via this.ActionRequiresDevExpressScripts()"); } public static void ActionRequiresDevExpressScripts(this Controller that) { that.ViewData[Key] = true; } }