Asp.net-mvc – ASP.NET MVC ViewData if statement

asp.net-mvcviewdata

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

Best Answer

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
}