ASP.NET MVC ViewData if语句

Cam*_*ron 11 asp.net-mvc viewdata

我在我的视图中使用以下内容来检查是否存在类似domain.com/?query=moo的查询

if (!string.IsNullOrEmpty(Request.QueryString["query"])) { my code }

但现在需要更改它,以便检查ViewData查询是否存在而不是查询字符串,但不太确定如何重写它.我的ViewData看起来像这样:ViewData["query"]

有人可以帮忙吗?谢谢

hun*_*ter 18

if (ViewData["query"] != null) 
{
    // your code
}
Run Code Online (Sandbox Code Playgroud)

如果你必须得到一个字符串值,你可以这样做:

string query = (ViewData["query"] ?? string.Empty) as string;
if (!string.IsNullOrEmpty(query)) 
{
    // your code
}
Run Code Online (Sandbox Code Playgroud)


Rub*_*ink 5

用一些镀金来扩展猎人的答案......

ViewData Dictionary是光荣的无类型。

检查值是否存在的最简单方法(Hunter 的第一个示例)是:

if (ViewData.ContainsKey("query")) 
{
    // your code
}    
Run Code Online (Sandbox Code Playgroud)

您可以使用像 [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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这使人们可以将 Hunter 的第二个例子表示为:

String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))
Run Code Online (Sandbox Code Playgroud)

但总的来说,我喜欢将此类检查包装在意图揭示命名扩展方法中,例如:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这使得:

@if(ViewData.IncludesQuery())
{
Run Code Online (Sandbox Code Playgroud)

...

    var q = ViewData.Query();
}
Run Code Online (Sandbox Code Playgroud)

应用此技术的更详细示例:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)