考虑这个简单的控制器:
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);
}
现在,在我Create
看来,我想检查ViewBag
对象,看看它是否具有Error
属性。如果它具有错误属性,我需要在页面中注入一些 JavaScript,以向我的用户显示错误消息。
我创建了一个扩展方法来检查这一点:
public static bool Has (this object obj, string propertyName)
{
Type type = obj.GetType();
return type.GetProperty(propertyName) != null;
}
然后,在Create
视图中,我写了这行代码:
@if (ViewBag.Has("Error"))
{
// Injecting JavaScript here
}
但是,我收到此错误:
无法对空引用执行运行时绑定
任何想法?