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