检查ViewBag是否具有属性

检查ViewBag是否具有属性

本文介绍了检查ViewBag是否具有属性,以有条件地注入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);
}

现在,在我的创建 view,我想检查 ViewBag 对象,看看它是否有属性或不属性。如果它有错误属性,我需要在页面中注入一些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;
}

然后,在创建视图,我写了这行代码:

Then, in the Create view, I wrote this line of code:

@if (ViewBag.Has("Error"))
{
    // Injecting JavaScript here
}

但是,我得到这个错误:

However, I get this error:

任何想法?

推荐答案

您的代码不起作用,因为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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:25