ASP.NET MVC的ViewData if语句

20

我在我的视图中使用以下代码来检查是否存在查询参数,例如 domain.com/?query=moo

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

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

有人能帮忙吗?谢谢

4个回答

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

如果你非常需要获取一个字符串值,可以这样做:

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

我建议使用实际的转换而不是依赖于as(并扩展了此答案,提供了执行此操作的扩展:https://dev59.com/4G445IYBdhLWcg3w0dZD#35131514)。 - Ruben Bartelink

7

在Hunter的回答基础上,进一步解释一下...

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;
    }
}

这里有一个可以将Hunter的第二个例子表达出来的方法:
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
  <% if(ViewData["query"]!=null)
    { 
    if((!string.IsNullOrEmpty(ViewData["query"].ToString())) 
      {
        //code 
       }
    }
   %>

如果 ViewData["query"] == null,这将会出错。很多人试图对空值进行 ToString() 操作... 很多人都会出错。 - hunter
是的,已更新它。仍然检查空字符串以防万一! - Vishal

1
如果您曾经需要在一行中完成此操作-例如在Razor中。
ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "What I'm looking for"

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接