Search code examples
c#asp.netasp.net-mvcdynamic-controls

Adding dynamic controls to MVC and getting their values in Controller


Sorry for making it too long but you can see actual problem to get issue.

Background: Its a e-commerce project where I am allowing client to add any number of categories and subcategories under that. For each category client will create some attributes by himself. Suppose client created a category Mobile Phones and this category is added to Category table and then he creates some attributes to that category like Price,Brand etc and all these attributes are inserted into Attributes table with CategoryId (Primary Key of Categories table.). Its done so far.

While client adds a products in particular category, as an example in our Mobile Phones's Category and for saving products I have Products Table. Product table do not have columns Price and Brand initially but they will be created when client creates an attribute hence I don't know all these columns at development time.

While creating an attribute client will also fill some information regarding that attribute i.e

  1. Name of attribute
  2. Display Name
  3. Server Control like TextBox,Dropdown etc
  4. Validations

Actual Problem:

Looking at above story, we came to know that we may have any number of attribute for any category and those attributes will have Server Control associated. While adding those controls on view while adding a product, we need to add only associated control dynamically, not HTML or Razor. Can we do this in MVC.? If yes then how?

Thanks.


Solution

  • You can use a Dictionary or an array as a parameter in your controller's actions. In the view you'll only need to name all your inputs as if they were an array:

    <input type="text" name="data[1]" >
    <input type="text" name="data[2]" >
    

    Here's a sample: http://www.quickstepit.net/mvc-3-model-binding-array/

    The same thing goes for selects.