Checking to see if ViewBag has a property or not, to conditionally inject JavaScript

52,072

Solution 1

Your code doesnt work because ViewBag is a dynamic object not a 'real' type.

the following code should work:

public static bool Has (this object obj, string propertyName) 
{
    var dynamic = obj as DynamicObject;
    if(dynamic == null) return false;
    return dynamic.GetDynamicMemberNames().Contains(propertyName);
}

Solution 2

@if (ViewBag.Error!=null)
{
    // Injecting JavaScript here
}

Solution 3

Instead of using the ViewBag, use ViewData so you can check for the of the item you are storing. The ViewData object is used as Dictionary of objects that you can reference by key, it is not a dynamic as the ViewBag.

// Set the [ViewData][1] in the controller
ViewData["hideSearchForm"] = true;    

// Use the condition in the view
if(Convert.ToBoolean(ViewData["hideSearchForm"])
    hideSearchForm();

Solution 4

I would avoid ViewBag here completely. See my thoughts here on this: http://completedevelopment.blogspot.com/2011/12/stop-using-viewbag-in-most-places.html

The alternative would be to throw a custom error and catch it. how do you know if the database is down, or if its a business logic save error? in the example above you just catch a single exception, generally there is a better way to catch each exception type, and then a general exception handler for the truly unhandled exceptions such as the built in custom error pages or using ELMAH.

So above, I would instead ModelState.AddModelError() You can then look at these errors (assuming you arent jsut going to use the built in validation) via How do I access the ModelState from within my View (aspx page)?

So please carefully consider displaying a message when you catch 'any' exception.

Solution 5

You can use ViewData.ContainsKey("yourkey").

In controller:

ViewBag.IsExist = true;

In view:

if(ViewData.ContainsKey("IsExist")) {...}
Share:
52,072
Saeed Neamati
Author by

Saeed Neamati

I love food, and I eat a lot.

Updated on July 16, 2021

Comments

  • Saeed Neamati
    Saeed Neamati almost 3 years

    Consider this simple controller:

    Porduct product = new Product(){
      // Creating a product object;
    };
    try
    {
       productManager.SaveProduct(product);
       return RedirectToAction("List");
    }
    catch (Exception ex)
    {
       ViewBag.ErrorMessage = ex.Message;
       return View("Create", product);
    }
    

    Now, in my Create view, I want to check ViewBag object, to see if it has Error property or not. If it has the error property, I need to inject some JavaScript into the page, to show the error message to my user.

    I created an extension method to check this:

    public static bool Has (this object obj, string propertyName) 
    {
        Type type = obj.GetType();
        return type.GetProperty(propertyName) != null;
    }
    

    Then, in the Create view, I wrote this line of code:

    @if (ViewBag.Has("Error"))
    {
        // Injecting JavaScript here
    }
    

    However, I get this error:

    Cannot perform runtime binding on a null reference

    Any idea?