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?
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.
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.
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.
@if (ViewBag.Error!=null) { // Injecting JavaScript here }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With