Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 880
Cameron Avatar asked Jan 13 '11 16:01

Cameron


People also ask

What is ViewData in MVC with example?

ViewData is a dictionary of objects that are stored and retrieved using strings as keys. It is used to transfer data from Controller to View. Since ViewData is a dictionary, it contains key-value pairs where each key must be a string. ViewData only transfers data from controller to view, not vice-versa.

What is the use of ViewData in MVC?

In MVC, when we want to transfer the data from the controller to view, we use ViewData. It is a dictionary type that stores the data internally. ViewData contains key-value pairs which means each key must be a string in a dictionary. The only limitation of ViewData is, it can transfer data from controller to view.

Why ViewData is faster than ViewBag?

Requires typecasting for complex data type and checks for null values to avoid error. If redirection occurs, then its value becomes null. ViewData is faster than ViewBag.

When should we use ViewData?

All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).


2 Answers

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
}
like image 64
hunter Avatar answered Sep 22 '22 23:09

hunter


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;
    }
}
like image 23
Ruben Bartelink Avatar answered Sep 22 '22 23:09

Ruben Bartelink