Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a class like ASP.NET MVC 3 ViewBag?

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?

like image 306
Alex Hope O'Connor Avatar asked Apr 26 '11 23:04

Alex Hope O'Connor


People also ask

What is ASP.NET MVC ViewBag?

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.

What is ViewBag and ViewData?

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.

Which is faster ViewBag or ViewData?

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.

What is ViewBag ViewData and TempData?

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.


1 Answers

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

like image 82
Carlos R Balebona Avatar answered Oct 16 '22 00:10

Carlos R Balebona