简体   繁体   中英

How to create a strongly typed view during runtime in ASP.NET MVC?

I am using ASP.NET MVC and there's a need to creates new views during runtime based on user selections. These views once created, need to be saved in storage so that they can be reused. I prefer these views to be strongly typed. Naturally the model class for each new view doesn't exist and these classes will have new properties according to what the user creates.

For example, if a user selects a textbox and wants it to be used for firstname, eventually I would like to have a class created dynamically with a public property called FirstName... and so on. Everything is created on the fly.

I would like to get ideas on how to approach this. Would Dynamic Source Code Generation and Compilation work for this workflow or is this complicating it more than it should?

Update:
One use case is if a form is needed to be created based on a user selection of a database table. If there are hundreds of tables, I won't be creating hundreds of views. I know I can maybe use a gridview in this example but for all the cases, a dynamic view is more appropriate.

Your user selections are data, not code:

  • Create data-structures based on the user selections.
  • Save them in a database for later.
  • Write a view which takes those data-structures (as a model) and displays them.
  • EditorTemplates can be used to display each individual control, using strongly-typed views.

Data

 public class Page
 {
     public List<Control> Controls { get; set; }
 }

 public class Textbox : Control
 {
     public string Label { get; set; }
     public string Value { get; set; }
 }

Page.cshtml

@model Page

@for (int i 0; i < Model.Controls.Count; i++)
{
     // Render using the EditorTemplate view for the control's type
     @Html.EditorFor(m => m.Controls[i])
}

EditorTemplates/Textbox.cshtml

@model Textbox

@Html.HiddenFor(m => m.ControlId)

@Html.LabelFor(m => m.Value, Model.Label)
@Html.TextBoxFor(m => m.Value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM