检查 ViewBag 是否有属性,有条件地注入 JavaScript [英] Checking to see if ViewBag has a property or not, to conditionally inject JavaScript
问题描述
考虑这个简单的控制器:
Consider this simple 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
属性.如果它有错误属性,我需要在页面中注入一些 JavaScript,以向我的用户显示错误消息.
Now, in my Create
view, I want to check ViewBag
object, to see if it has Error
property or not. If it has the error property, I need to inject some JavaScript into the page, to show the error message to my user.
我创建了一个扩展方法来检查这个:
I created an extension method to check this:
public static bool Has (this object obj, string propertyName)
{
Type type = obj.GetType();
return type.GetProperty(propertyName) != null;
}
然后,在Create
视图中,我写了这行代码:
Then, in the Create
view, I wrote this line of code:
@if (ViewBag.Has("Error"))
{
// Injecting JavaScript here
}
但是,我收到此错误:
无法对空引用执行运行时绑定
Cannot perform runtime binding on a null reference
有什么想法吗?
推荐答案
您的代码不起作用,因为 ViewBag 是一个 动态对象 不是真实"类型.
Your code doesnt work because ViewBag is a dynamic object not a 'real' type.
以下代码应该可以工作:
the following code should work:
public static bool Has (this object obj, string propertyName)
{
var dynamic = obj as DynamicObject;
if(dynamic == null) return false;
return dynamic.GetDynamicMemberNames().Contains(propertyName);
}
这篇关于检查 ViewBag 是否有属性,有条件地注入 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!