考虑这个简单的控制器:
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); }
现在,在我的创建视图中,我想检查ViewBag对象,看看它是否有Error属性。如果它有error属性,我需要注入一些JavaScript到页面中,以显示错误消息给我的用户。
public static bool Has (this object obj,string propertyName) { Type type = obj.GetType(); return type.GetProperty(propertyName) != null; }
然后,在创建视图中,我写了这行代码:
@if (ViewBag.Has("Error")) { // Injecting JavaScript here }
但是,我得到这个错误:
Cannot perform runtime binding on a null reference
任何想法?