代码之家  ›  专栏  ›  技术社区  ›  Bassie

可以从ModelMetaData.Properties动态创建输入字段吗?

  •  0
  • Bassie  · 技术社区  · 8 年前

    ViewData.ModelMetadata.Properties

    @foreach (var property in ViewData.ModelMetadata.Properties
                    .Where(p => (p.AdditionalValues.Count > 0) && ((bool)p.AdditionalValues["tags"])))
    {
        // Generate form here
    }
    

    我能够显示 LabelFor 正确使用

    @Html.LabelFor(model => Model, 
        property.DisplayName, 
        htmlAttributes: new { @class = "control-label col-md-2" })
    

    但我似乎无法让编辑工作。

    我试过了

    @Html.HiddenFor(model => model.GetType().GetProperties().First(t=>t.Name == property.PropertyName))
    

    模板只能用于字段访问、属性访问、一维数组索引或单参数自定义索引器表达式。

    我也试过了

    @Html.HiddenFor(model => property)
    

    null

    可以这样做吗,或者我需要手动编码每个输入?

    1 回复  |  直到 8 年前
        1
  •  0
  •   Bassie    8 年前

    我通过以下方式解决了这个问题:

    <input class="form-control" id="@($"{property.PropertyName}Field")"
           name="@property.PropertyName" type="hidden" value="" />
    

    现在这个值传递给控制器。

    我想它只需要 name 属性以匹配 ViewModel