Generating views at runtime from a database table

527 Views Asked by At

I have a technical question as to how I can generate Multiviews (views control) using MVC framework where the views are getting generated dynamically (get details from the DB).

As per asp.net the generation of the views (control) will need to be placed in PreInit or Load events of the page. Need some technical guidance on how to go ahead.

Or is it good practice to use again the question is how to. Any other alternate solution is also welcome..

1

There are 1 best solutions below

0
On

You should probably try something like this:

Generating ASP.NET MVC View Controls According to XML Configurations

The data source is XML, but that doesn't matter; you should be able to adapt the technique to a database table containing the view metadata.

The "meta-view" code for an editor form would look something like this:

@model DynamicControlsCreation.ViewModels.DefaultControlsViewModel 
<p>
    @using (Html.BeginForm())
    {
        for (int i = 0; i < Model.Controls.Count; i++)
        {         
        <div>
            @Html.HiddenFor(x => x.Controls[i].Type)
            @Html.HiddenFor(x => x.Controls[i].Name)
            @Html.EditorFor(x => x.Controls[i])
        </div>       
        } 

        <input type="submit" value="Submit" /> 
    }
</p>

Note that you don't get much "shape" when you generate a view in this manner; it's mostly useful for things like configuration forms. Although you can put metadata in the database like the locations of the controls on the page, by the time you do all that, you're probably better off just making conventional views.