I have a situation where I would like to do something simular to what was done with the ASP.NET MVC 3 ViewBag object where properties are created at runtime? Or is it at compile time?
Anyway I was wondering how to go about creating an object with this behaviour?
ViewBag is a property – considered a dynamic object – that enables you to share values dynamically between the controller and view within ASP.NET MVC applications.
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error.
Requires typecasting for complex data type and checks for null values to avoid error. If redirection occurs, then its value becomes null. ViewData is faster than ViewBag.
To summarize, ViewBag and ViewData are used to pass the data from Controller action to View and TempData is used to pass the data from action to another action or one Controller to another Controller.
I created something like this:
public class MyBag : DynamicObject
{
private readonly Dictionary<string, dynamic> _properties = new Dictionary<string, dynamic>( StringComparer.InvariantCultureIgnoreCase );
public override bool TryGetMember( GetMemberBinder binder, out dynamic result )
{
result = this._properties.ContainsKey( binder.Name ) ? this._properties[ binder.Name ] : null;
return true;
}
public override bool TrySetMember( SetMemberBinder binder, dynamic value )
{
if( value == null )
{
if( _properties.ContainsKey( binder.Name ) )
_properties.Remove( binder.Name );
}
else
_properties[ binder.Name ] = value;
return true;
}
}
then you can use it like this:
dynamic bag = new MyBag();
bag.Apples = 4;
bag.ApplesBrand = "some brand";
MessageBox.Show( string.Format( "Apples: {0}, Brand: {1}, Non-Existing-Key: {2}", bag.Apples, bag.ApplesBrand, bag.JAJA ) );
note that entry for "JAJA" was never created ... and still doesn't throw an exception, just returns null
hope this helps somebody
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