考虑这个简单的控制器:
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); }@H_404_4@现在,在我的创建视图中,我想检查ViewBag对象,看看它是否有Error属性。如果它有error属性,我需要注入一些JavaScript到页面中,以显示错误消息给我的用户。 @H_404_4@我创建了一个扩展方法来检查:
public static bool Has (this object obj,string propertyName) { Type type = obj.GetType(); return type.GetProperty(propertyName) != null; }@H_404_4@然后,在创建视图中,我写了这行代码:
@if (ViewBag.Has("Error")) { // Injecting JavaScript here }@H_404_4@但是,我得到这个错误:
@H_404_4@Cannot perform runtime binding on a null reference@H_404_4@任何想法?
解决方法
你的代码不工作,因为ViewBag是一个
dyanmic object不是一个’真实’类型。
@H_404_4@以下代码应该工作:
public static bool Has (this object obj,string propertyName) { var dynamic = obj as DynamicObject; if(dynamic == null) return false; return dynamic.GetDynamicMemberNames().Contains(propertyName); }