asp.net-mvc ASP.NET MVC ViewData if 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4682143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:43:33  来源:igfitidea点击:

ASP.NET MVC ViewData if statement

asp.net-mvcviewdata

提问by Cameron

I use the following in my View to check if a query exists like domain.com/?query=moo

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

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

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

But now need to change it so that it checks if the ViewData query exists instead of the query string, but not quite sure how to rewrite it. My ViewData looks like this: ViewData["query"]

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

Can anyone help? Thanks

任何人都可以帮忙吗?谢谢

回答by hunter

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

if you absolutely have to get a string value you can do:

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

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

回答by Ruben Bartelink

Expanding on Hunter's answer with some goldplating...

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

The ViewDataDictionaryis gloriously untyped.

ViewDataDictionary是光荣的无类型。

The simplest way to check for presence of a value (Hunter's first example) is:

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

if (ViewData.ContainsKey("query")) 
{
    // your code
}    

You can use a wrapper like [1]:

您可以使用像 [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;
    }
}

which enables one to express Hunter's second example as:

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

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

But in general, I like to wrap such checks in intention revealing named extension methods, e.g.:

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

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

Which enables:

这使得:

@if(ViewData.IncludesQuery())
{

...

...

    var q = ViewData.Query();
}

A more elaborate example of applying this technique:

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

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

回答by Vishal

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

回答by Matty Bear

If you ever had to do this in one line - for example in Razor

如果您不得不在一行中执行此操作 - 例如在 Razor 中

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

I'm trying to use ViewData to figure out whether or not the current Action is the one that needs to be Active in my navigation bar

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

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