C# 在MVC4中呈现动态表单控件

C# 在MVC4中呈现动态表单控件,c#,asp.net-mvc-4,C#,Asp.net Mvc 4,我想生成动态表单控件,表单变量及其各自的数据类型存储在MySql DB表中。这是我用来在窗体上呈现主变量的代码。但我尝试过的选择有一些或其他问题。守则如下: Labels.cs public partial class Labels { public int Label_Id { get; set; } public string Label_Name { get; set; } public string Form_Element_Type { get; set; } }

我想生成动态表单控件,表单变量及其各自的数据类型存储在MySql DB表中。这是我用来在窗体上呈现主变量的代码。但我尝试过的选择有一些或其他问题。守则如下:

Labels.cs

public partial class Labels
{
   public int Label_Id { get; set; }
   public string Label_Name { get; set; }
   public string Form_Element_Type { get; set; }
}

public partial class Observation
{
   public int Observation_Id {get; set;}
   public int Employee_Id {get; set;}
   public int Label_Id {get; set;}
   public string Value {get; set;}
}
模范班

public class EmployeeModel
{
   public Dictionary<string, string> ObsDictionay { get; set; }
}
此选项使用所有值将obditionay重新调谐到控制器中的[HttpPost]方法,但所有变量的呈现文本框除外

选项3:

<input class="control-label" type="@item.Form_Element_Type" id="@item.Master_Label_Id" name="@item.Master_Label_Id "  value= @Model.ObsDictionay[item.Label_Id.ToString()]">
@Html.EditorFor(x => x.ObsDictionay[item.Label_Id.ToString()])
@if (item.Form_Element_Type == "checkbox")
{
     @Html.CheckBoxFor(x => x.ObsDictionay[item.Label_Id.ToString()] == "Y"? true : false)
}
else if(item.Form_Element_Type == "textbox")
{
@Html.TextAreaFor(x => x.ObsDictionay[item.Label_Id.ToString()])                                        
 }
错误:System.InvalidOperationException:模板只能在呈现复选框时与字段访问、属性访问、一维数组索引或单参数自定义索引器表达式一起使用。


有人能帮我吗。

选项1


应该是
,我在其中一个项目中使用过动态表单,也写过。我发现Expando对象和动态类型视图更适合选项1,因为模型绑定是按属性名称完成的。不要使用“@item.Master\u Label\u Id”这样的名称,尝试使用“@item.obstictionay[item.Label\u Id.ToString()]”这样的控件名称选项3--@Html.CheckBoxFor(x=>x.obstictionay[item.Label\u Id.ToString()],新的{Value=Model.obstictionay[item.Label\u Id.ToString()]=“Y”?true:false)x=>x.obstictionary[item.Label\u Id.ToString()]给出错误“无法将类型字符串隐式转换为bool”……有帮助吗?/@user1414935-您可以发布将输入值绑定到模型属性的操作代码吗?请参阅上面的控制器代码“EmployeeController”和HttpPost方法[HttpPost]公共操作结果ProcessEmployee(EmployeeModel model,FormCollection collection){return View();}单击submit按钮,代码将命中HttpPost方法,但参数中的model将obsDictionary对象包含为null
@if (item.Form_Element_Type == "checkbox")
{
     @Html.CheckBoxFor(x => x.ObsDictionay[item.Label_Id.ToString()] == "Y"? true : false)
}
else if(item.Form_Element_Type == "textbox")
{
@Html.TextAreaFor(x => x.ObsDictionay[item.Label_Id.ToString()])                                        
 }