【问题标题】:Dynamic forms in ASP .netASP .net 中的动态表单
【发布时间】:2018-07-11 08:41:14
【问题描述】:

我有 Property 表,它有 Id 和 Name。

我需要为这些属性动态地编写一个表单。

我尝试过这样的事情:

@foreach (var item in Model.Properties) {
                                <div class="col-md-6 margin_top_15">
                                    @Html.LabelFor(m => item.Name, new {@class = "col-md-2 control-label"})
                                    <div class="col-md-10">
                                        @Html.TextBoxFor(m => item.Name, new {@class = "form-control"})
                                        @Html.ValidationMessageFor(m => item.Name, "", new {@class = "text-danger"})
                                    </div>
                                </div>
}

问题是我得到这样的形式:

我明白为什么会发生这种情况,因为属性名称总是相同的名称 - “名称”。

型号是:

public class PropertyField {
        [Key]
        public int FieldId { get; set; }
        public string FieldName { get; set; }
        public string FieldValue { get; set; }
}

我可以将 LabelFor 更改为 Label 并获得良好的字段外观,但提交模型为空:

@Html.Label(item.FieldName, new {@class = "col-md-2 control-label"})

【问题讨论】:

    标签: c# asp.net forms entity


    【解决方案1】:

    尝试将foreach 循环改为标准for 循环,因为为多个元素生成相同的元素ID 会产生无效标记:

    // assumed that Model.Properties has type of List<PropertyField>
    
    @for (var i = 0; i < Model.Properties.Count(); i++)
    {
        <div class="col-md-6 margin_top_15">
        @Html.LabelFor(m => Model.Properties[i].FieldName, new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
            @Html.TextBoxFor(m => Model.Properties[i].FieldName, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => Model.Properties[i].FieldName, "", new { @class = "text-danger" })
            </div>
        </div>
    }
    

    通过使用foreach循环,MVC默认模型绑定器无法正确绑定视图页面中的所有属性,因为某些HTML元素命名不正确,因此提交表单后列表集合包含空值。

    相关问题:

    For each loop with controls and submitting form (Html.BeginForm) in MVC 4

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      相关资源
      最近更新 更多