ASP.NET MVC ViewData if 语句

发布于 2024-10-12 00:53:58 字数 268 浏览 9 评论 0原文

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

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

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

有人可以帮忙吗?谢谢

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

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"]

Can anyone help? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

葬﹪忆之殇 2024-10-19 00:53:58
if (ViewData["query"] != null) 
{
    // your code
}

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

string query = (ViewData["query"] ?? string.Empty) as string;
if (!string.IsNullOrEmpty(query)) 
{
    // your code
}
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
}
冰雪梦之恋 2024-10-19 00:53:58

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

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

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

The ViewData Dictionary is gloriously untyped.

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

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

You can use a wrapper like [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:

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;
    }
}
总攻大人 2024-10-19 00:53:58
  <% if(ViewData["query"]!=null)
    { 
    if((!string.IsNullOrEmpty(ViewData["query"].ToString())) 
      {
        //code 
       }
    }
   %>
  <% if(ViewData["query"]!=null)
    { 
    if((!string.IsNullOrEmpty(ViewData["query"].ToString())) 
      {
        //code 
       }
    }
   %>
心舞飞扬 2024-10-19 00:53:58

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

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

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

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

If you ever had to do this in one line - for example in 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

<li class="@(ViewData["NavigationLocation"] != null && ViewData["NavigationLocation"].ToString() == "Configuration" ? "active" : null)">
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文