考虑这个简单的 Controller :
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
属性(property)与否。如果它具有错误属性,我需要在页面中注入(inject)一些 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
}
但是,我收到此错误:
Cannot perform runtime binding on a null reference
任何的想法?
最佳答案
您的代码不起作用,因为 ViewBag 是 dynamic object不是“真正的”类型。
以下代码应该可以工作:
public static bool Has (this object obj, string propertyName)
{
var dynamic = obj as DynamicObject;
if(dynamic == null) return false;
return dynamic.GetDynamicMemberNames().Contains(propertyName);
}
关于asp.net-mvc-3 - 检查 ViewBag 是否有属性,以有条件地注入(inject) JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8640927/