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

后端 未结 5 1120
轮回少年
轮回少年 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: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.

提交回复
热议问题