检查是否ViewBag有一个属性或没有,有条件的JavaScript注入 [英] Checking to see if ViewBag has a property or not, to conditionally inject JavaScript

查看:467
本文介绍了检查是否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);
}

现在,在我的创建的看法,我想检查 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;
}

然后,在创建的看法,我写了这行code的:

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

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

不过,我得到这个错误:

However, I get this error:

无法对null引用执行运行时绑定

Cannot perform runtime binding on a null reference

任何想法?

推荐答案

您code不起作用,因为ViewBag是的 dyanmic对象不是一个'真正的'类型。

Your code doesnt work because ViewBag is a dyanmic object not a 'real' type.

以下code应该工作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆