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

后端 未结 5 1100
轮回少年
轮回少年 2020-12-09 02:04

Consider this simple controller:

Porduct product = new Product(){
  // Creating a product object;
};
try
{
   productManager.SaveProduct(product);
   return          


        
相关标签:
5条回答
  • 2020-12-09 02:09

    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();
    
    0 讨论(0)
  • 2020-12-09 02:12

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

    In controller:

    ViewBag.IsExist = true;
    

    In view:

    if(ViewData.ContainsKey("IsExist")) {...}
    
    0 讨论(0)
  • 2020-12-09 02:14

    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);
    }
    
    0 讨论(0)
  • 2020-12-09 02:20
    @if (ViewBag.Error!=null)
    {
        // Injecting JavaScript here
    }
    
    0 讨论(0)
  • 2020-12-09 02:20

    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.

    0 讨论(0)
提交回复
热议问题