Search code examples
asp.net-mvcviewdata

ASP.NET MVC ViewData if statement


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


Solution

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