Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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); } 

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:

Cannot perform runtime binding on a null reference

Any idea?

like image 310
Saeed Neamati Avatar asked Dec 27 '11 03:12

Saeed Neamati


People also ask

How do you know if a ViewBag is worth anything?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.

What is the type of the ViewBag property?

In general, ViewBag is a way to pass data from the controller to the view. It is a type object and is a dynamic property under the controller base class.

What does the ViewData property do?

ViewData is a dictionary of objects that are stored and retrieved using strings as keys. It is used to transfer data from Controller to View. Since ViewData is a dictionary, it contains key-value pairs where each key must be a string. ViewData only transfers data from controller to view, not vice-versa.


2 Answers

@if (ViewBag.Error!=null) {     // Injecting JavaScript here } 
like image 191
jazzcat Avatar answered Sep 28 '22 10:09

jazzcat


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); } 
like image 31
JeffreyABecker Avatar answered Sep 28 '22 11:09

JeffreyABecker