c# - 如何在运行时在 ASP.NET MVC 中创建强类型 View ?

标签 c# .net asp.net-mvc dynamic

我正在使用 ASP.NET MVC,需要在运行时根据用户选择创建新 View 。这些 View 一旦创建,就需要保存在存储器中以便可以重复使用。我更喜欢这些 View 是强类型的。当然,每个新 View 的模型类都不存在,这些类将根据用户创建的内容具有新属性。

例如,如果用户选择一个文本框并希望将其用于名字,最终我希望动态创建一个类,该类具有名为 FirstName 的公共(public)属性...等等。一切都是即时创建的。

我想了解如何解决这个问题。会 Dynamic Source Code Generation and Compilation为这个工作流程工作,还是使它变得比它应该的更复杂?

更新:
一个用例是,是否需要根据用户对数据库表的选择来创建表单。如果有数百个表,我不会创建数百个 View 。我知道我可以在此示例中使用 GridView ,但对于所有情况,动态 View 更合适。

最佳答案

您的用户选择是数据,而不是代码:

  • 根据用户选择创建数据结构。
  • 将它们保存在数据库中以备后用。
  • 编写一个采用这些数据结构(作为模型)并显示它们的 View 。
  • EditorTemplates可用于显示每个单独的控件,使用强类型 View 。

数据

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

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

页面.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)

关于c# - 如何在运行时在 ASP.NET MVC 中创建强类型 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30630089/

相关文章:

c# - 将 1d 数组索引转换为 3d 数组索引?

c# - WCF Web 服务的响应大小限制

c# - Entity Framework 的 ODAC 输出格式错误的 SQL?

asp.net-mvc - ASP.NET MVC 中的空 SelectList

c# - 如何使用 cultureinfo 删除千位分隔符?

c# - 单元测试依赖于其他公共(public)方法的方法

C# 代码优化导致 Interlocked.Exchange() 出现问题

c# - 使用窗口句柄获取 IUnkown

sql-server - Elmah 不在 IIS7 服务器上工作

c# - 部分 View 提交