1

I want to create an array of dynamic objects, similar to the JSON pattern. I am using this to allow my Breadcrumb class take in argumens that define the output characteristics. I am thinking it would look something like this

breadcrumbs.Add(new Breadcrumb() { 
    Title = "Page name", 
    Attributes = { class = "myclass", data-info="info stuff" } 
});

I would then iterate through this array when I display the breadcrum to output something like this

<a href="" title="Page name" class="myclass" data=info="into stuff">...</a>

The question is can I do this dynamically without creating boiler plate code to sit inbetween i.e. BreadcrumAttribute that may specify the attribute name and then data.

I have seen a similar pattern elsewhere within MVC.NET but cannot remember where it was...

2 Answers 2

4

you can use anonymous type like this:

breadcrumbs.Add(new Breadcrumb() { 
    Title = "Page name", 
    Attributes = new { @class = "myclass", datainfo="info stuff" } 
});

data-info is not allowed as property name so I changed it to datainfo, you can name it also data_info

or define it as Dictionary<string,string> and use it like:

breadcrumbs.Add(new Breadcrumb() { 
    Title = "Page name", 
    Attributes = new Dictionary<string, string>() { { "class", "myclass" }, { "data-info", "info" } }
});
Sign up to request clarification or add additional context in comments.

4 Comments

This looks like what I'm after - What type would Attributes be?
@Chris they will be AnonymousType msdn.microsoft.com/en-us/library/bb397696.aspx
How do I define that as part of a class though? I cannot use var within a class definition...
@Chris define it as Object, or use second solution with dictionaries. You can also use dynamic instead of Object
1

Make Breadcrumb.Attributes a Dictionary

class Breadcrumb {
    public string Title;
    public Dictionary<string,string> Attributes;
}

and then..

        var breadcrumbs = new List<Breadcrumb>
            {
                new Breadcrumb()
                    {
                        Title = "Page name",
                        Attributes =
                            new Dictionary<string, string>
                                {
                                    {"class", "myclass"}, 
                                    {"data-info", "info stuff"}
                                }
                    }
            };

2 Comments

You know, I was so busy thinking about clever things I never even thought to think simple. Thanks!
The other answer is probably more elegant though !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.