ASP.NET MVC ViewData if语句

时间:2011-01-13 16:01:06

标签: asp.net-mvc viewdata

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

的查询

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

但现在需要更改它,以便检查ViewData查询是否存在而不是查询字符串,但不太确定如何重写它。我的ViewData如下所示:ViewData["query"]

有人可以帮忙吗?感谢

4 个答案:

答案 0 :(得分:17)

if (ViewData["query"] != null) 
{
    // your code
}

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

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

答案 1 :(得分:3)

  <% if(ViewData["query"]!=null)
    { 
    if((!string.IsNullOrEmpty(ViewData["query"].ToString())) 
      {
        //code 
       }
    }
   %>

答案 2 :(得分:3)

通过一些镀金来扩展亨特的答案......

ViewData Dictionary光荣无比。

检查值是否存在的最简单方法(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;
    }
}

答案 3 :(得分:1)

如果您必须在一行中执行此操作 - 例如在Razor中

ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "What I'm looking for"

我正在尝试使用ViewData来确定当前的Action是否是我的导航栏中需要处于Active状态的Action

<li class="@(ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "Configuration" ? "active" : null)">