【发布时间】:2019-01-22 19:51:24
【问题描述】:
我一直在尝试为我正在忙于设计的情况找到解决方案,但是我没有设法解决。
想象一下有以下模型
public enum InputType
{
TextInput,
LookupInput
}
public struct AdditionalProperty
{
public string Key {get;set;}
public string Value {get;set;}
public InputType Type {get;set;}
}
public class Person
{
public string FirstName {get;set;}
public List<AdditionalProperty> AdditionalProperties {get;set;}
}
然后,有以下控制器
public class HomeController
{
public ActionResult Index()
{
var model = new Person { FirstName = "MyName" };
model.AdditionalProperties = new List<AdditionalProperty>();
var listItem = new AdditionalProperty
{
Key = "Surname",
Value = "MySurname"
};
model.AdditionalProperties.Add(listItem);
return View(model)
}
}
我正在寻找的是关于如何“动态”创建具有正确输入类型的属性的 Razor 视图代码,绑定到某些东西,以便我能够在表单被回发时仍然使用模型到控制器的保存功能。
所以已知的属性应该是这样的:
<div class="form-group">
<div class="form-row">
<div class="col-md-6">
@Html.LabelFor(model => model.FirstName, new { @class = "control-label" })
<div>
@Html.TextBoxFor(model => model.FirstName, new { @class = "form-control", placeholder = "Enter Group Name", type = "text" })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
</div>
</div>
然后的想法是有以下。显然以下是不够的,这就是我需要帮助的地方。 我想根据 property.InputType 显示其他属性,一个在另一个之下,每个在单独的行上(使用引导行)。
@foreach (var property in Model.Properties)
{
@Html.LabelFor(model => property.Key, new { @class = "control-label" })
<div>
@if (property.InputType == TextInput)
{
@Html.TextBoxFor(model => property.Value, new { @class = "form-control", placeholder = "Enter Group Name", type = "text" })
}
@Html.ValidationMessageFor(model => property.Key, "", new { @class = "text-danger" })
</div>
}
因此,我希望将我的观点视为:
| <label> | <input>
Known Property | FirstName | MyFirstName
Unknown Property | Surname | MySurname
【问题讨论】:
-
你不能使用
foreach循环为集合生成表单控件(请参阅Post an HTML Table to ADO.NET DataTable。生成<label>的代码需要是@Html.LabelFor(m => AdditionalProperties[i].Key, Model.AdditionalProperties[i].Key, new { ... })。但是那种逻辑应该在自定义HtmlHelper方法中转义,而不是视图。此外,您的ValidationMessageFor()有点毫无意义,因为您没有验证 -
斯蒂芬,有没有可能是因为你没有回答我的问题
-
是的,这是可能的(但使用
for循环或自定义EditorTemplate以便正确生成表单控件的name属性 - 请参阅我的第一条评论中的链接) -
我知道在处理索引时我应该使用 for。我正在努力解决的概念是为某个项目填充正确的 InputType(文本框、组合框等)
-
为了使用不同的编辑器模板,我必须根据我提到的类型为每个属性使用不同的模型。
标签: asp.net-mvc razor dynamic view binding