ASP.NET MVC ViewData if statement

Cameron picture Cameron · Jan 13, 2011 · Viewed 24.3k times · Source

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

Answer

hunter picture hunter · Jan 13, 2011
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
}