简体   繁体   English

如何在ASP.NET MVC运行时创建强类型视图?

[英]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. 我正在使用ASP.NET MVC,并且需要在运行时根据用户选择创建新视图。 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. 例如,如果用户选择一个文本框并希望它用于firstname,那么最终我希望使用名为FirstName的公共属性动态创建一个类......依此类推。 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. 我知道我可以在这个例子中使用gridview,但对于所有情况,动态视图更合适。

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. EditorTemplates可用于显示每个单独的控件,使用强类型视图。

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 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 EditorTemplates / Textbox.cshtml

@model Textbox

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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