我想要生成动态表单控件,其中表单变量及其各自的数据类型存储在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; }
}控制器
Public class EmployeeController
{
Public ActionResult ProcessEmployee ()
{
List<MasterLabel> masterLabels = new List<MasterLabel>();
IMasterLabel masterLabelManager = new MasterLabelsManager();
masterLabels = masterLabelManager.GetAll();
model.MasterLabels = masterLabels;
IObservation obsManager = new ObservationManager();
List<Observation> obsList = new List<Observation>();
obsList = obsManager.GetAllByPatientId(id);
Dictionary<string, string> ObsDictionay = new Dictionary<string, string>();
foreach (var label in masterLabels)
{
int flag = 0;
if (obsList.Count() > 0)
{
foreach (var obs in obsList)
{
if (label.Label_Id == obs.Label_Id)
{
ObsDictionay.Add(label.Label_Id.ToString(), obs.Value);
flag = 1;
break;
}
}
if (flag == 0)
{
ObsDictionay.Add(label.Master_Label_Id.ToString(), null);
}
}
else
{
ObsDictionay.Add(label.Master_Label_Id.ToString(), null);
}
}
model.ObsDictionay = ObsDictionay;
}
}意见
选项1:
<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()]">此选项将空ObsDictionay还原为控制器中的HttpPost方法。
备选方案2:
@Html.EditorFor(x => x.ObsDictionay[item.Label_Id.ToString()])此选项将ObsDictionay还原为带有所有值的控制器中的HttpPost方法,但呈现所有变量的文本框。
选项3:
@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:模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式,同时呈现复选框.。
有人能帮我解决这个问题吗。
发布于 2015-05-13 07:11:07
选项1
应该是<input class="control-label" type="@item.Form_Element_Type" id="@item.Master_Label_Id" name="@item.Master_Label_Name " value= @Model.ObsDictionay[item.Label_Id.ToString()]">吗
我也不知道为什么你有@item.Master_Label_Id而不是@item.Label_Id。
选项2
问题是@Html.EditorFor取决于属性类型,因为所有字段都是string,textbox是所选的输入。为了使它正常工作,您必须使用不同的字段类型(可能通过传递object并将其安全地转换为所需的类型)。
选项3
我不认为@Html.CheckBoxFor(x => x.ObsDictionay[item.Label_Id.ToString()] == "Y"? true : false)是有效的原因,因为我记得您必须将表达式作为第一个参数传递。将其更改为@Html.CheckBoxFor(x => x.ObsDictionay[item.Label_Id.ToString()], new { Value = Model.ObsDictionay[item.Label_Id.ToString()] == "Y" ? true : false)
https://stackoverflow.com/questions/30207841
复制相似问题