How would you implement a model with “dynamic properties” with using mvc/razor? I really am not sure if “dynamic properties” is the correct term.
Scenario: I have a list of items from the DB. Each of these items are then given a set of “properties” from a list of attributes (also from the DB).
In my Item model I think I should have a collection of attributes/properties, correct? Something like
public class Item
{
public int ItemId { get; set; }
public string ItemName{ get; set; }
public virtual ICollection<Attribute> Attributes { get; set; }
}
public class Attribute
{
public int AttributeId { get; set; }
public string AttributeName { get; set; }
}
My goal is to render a view such that if a user selects an item from a dropdownlist, the set of properties associated with the selected item will be shown with the corresponding html input elements (either textbox or dropdownlist).
Example UI when a user selects an item from a dropdownlist (let’s say it is a “Camera”)
- Camera
- Brand – [textbox]
- Model – [textbox]
- Warranty – [dropdownlist of warranty length]
Example UI when a user selects an item from a dropdownlist (let’s say it is a “House”)
- House
- Floor Area – [textbox]
- Number of Rooms – [textbox]
- Number of Rooms – [textbox]
Creating/Editing/Deleting a straightforward model like the Attribute defined above is no problem. What’s throwing me off is the way to implement the “dynamic properties” described above.
I’m coming from WebForms and still quite new to MVC so take it easy on me ok? 🙂
As it turns out, this can easily be done just like any other model implementation. I just had to create “Item Templates” which contains the attributes and other meta-data related to the item’s attribute. Then I ask the user to pick a “template” so that I can update the list of attributes and the view accordingly. After that, the user can now fill out the corresponding values for each of the attributes in the template. The resulting model is a different model from the item template so there were partial views and editor templates involved.
I know this is not related to the question but I guess it’s worth mentioning that using View Models instead of the Domain Model eases things up. A lot.
Another thing that I had to do to make things a bit easier was to use a document-oriented storage instead of the traditional relational database as I think EAV-type of projects like this are more suited for NoSQL.
The next problem that I faced was how to validate the user’s input based on the data type of the attribute here.