ASP.NET MVC ViewData if语句

ASP.NET MVC ViewData if statement

我在视图中使用以下命令检查是否存在查询,例如domain.com/?query=moo

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

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

有人可以帮忙吗?谢谢


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

如果绝对必须获取字符串值,则可以执行以下操作:

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


通过镀金扩展猎人的答案...

ViewData Dictionary无类型。

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

1
2
3
4
if (ViewData.ContainsKey("query"))
{
    // your code
}

您可以使用[1]这样的package器:

1
2
3
4
5
6
7
8
9
10
11
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;
    }
}

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

1
String.IsNullOrEmpty(ViewData.ItemCastOrDefault<String>("query"))

但是总的来说,我希望将此类检查package起来,以揭示命名扩展方法,例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
    }
}

哪个启用:

1
2
@if(ViewData.IncludesQuery())
{

...

1
2
    var q = ViewData.Query();
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
    }
}

1
2
3
4
5
6
7
8
  <% if(ViewData["query"]!=null)
    {
    if((!string.IsNullOrEmpty(ViewData["query"].ToString()))
      {
        //code
       }
    }
   %>


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

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

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

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