使用data的表结构的屏幕截图
表结构如下:
Id | Category | DisplayName | FieldName | FieldType | FieldLength | IsRequired
详情请参见截图。
在选择类别时,应在视图中填充表中针对该类别定义的所有HTML字段。
以及如何在表单提交时验证。
我有400多个类别。
发布于 2019-06-10 04:23:55
这就是我认为你能做的。
首先声明一个任意名称的class
,我将使用SampleClass
public class SampleClass
{
public int Id { get; set; }
public string Category { get; set; }
public string DisplayName { get; set; }
public string FieldName { get; set; }
public string FieldType { get; set; }
public string FieldLength { get; set; }
public int IsRequired { get; set; }//you can convert this to boolean to make it easier
}
其次,从控制器中的db填充这个类
//assuming you are using linq query
var allEntry = context.Table.Where(m => m.Category == SelectedCategory);
var allViews = new List<SampleClass>();
foreach (var entry in allEntry)
{
allViews.Add(new SampleClass
{
FieldName = entry.FieldName,
//and so on...
});
}
第三,在视图中,按照我在评论中所说的那样做
@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { @class = "forms-horizontal", role = "form" }))
{
<div class="form-horizontal">
<h4>Title of the form</h4>
<hr /><br />
@foreach (var a in List<SampleClass>)//note this(List<SampleClass>) will be passed from the controller to the view.
{
switch (a.FieldType)
{
case "Test":
<div class="form-group">
<label for="@a.FieldName"></label>
<input id="@a.FieldName" type="text" name="@a.FieldName" required="@(a.IsRequired == 1 ? "required" : "")" />
</div>
break;
case "Number":
<div class="form-group">
<label for="@a.FieldName"></label>
<input id="@a.FieldName" type="number" name="@a.FieldName" required="@(a.IsRequired == 1 ? "required" : "")" />
</div>
break;
case "Select":
<div class="form-group">
<label for="@a.FieldName"></label>
@Html.DropDownList(a.FieldName, new SelectList(DbUtils.GetEvaluations(), "Value", "Text", null), "Select..", new { @required = @a.IsRequired == 1 ? "required" : "" })
</div>
break;
}
}
<div class="form-group">
<div class="col-md-offset-3 col-md-9">
<input type="submit" value="Submit" class="btn btn-primary" />
</div>
</div>
</div>
}
根据需要,您可以在select子句中使用更多的cases
。
希望这能帮上忙..
https://stackoverflow.com/questions/56516517
复制相似问题