2

这是我的模型:

public class Attribute
{
    public string Key { get; set; }
    public string Value{ get; set; }
}

我将其填写在我的 GET 创建中

    public ActionResult Create()
    {
        var Attributes = new[] 
        {
            new Attribute {Key = "Name" Value = "" },
            new Attribute {Key = "Age" Value = "" },
        };
        return View(Attributes);
    }

我的视图如下所示:

@model IEnumerable<Customers.ViewModels.Attribute>
@using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
        @foreach (var item in Model)
        {
            <div class="editor-label">
                @Html.Label(item.Key)
            </div>
            <div class="editor-field">
                @Html.EditorFor(m => item.Value)
                @Html.ValidationMessageFor(m => item.Value)
            </div>
        }
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

然后我的帖子创建看起来像这样:

    [HttpPost]
    public ActionResult Create(IEnumerable<Attribute> attributes)
    {
    }

但我IEnumerable<Attribute> attributes的为空。有什么建议么?

4

1 回答 1

3

您需要为 a 创建一个编辑器模板Attribute,然后将List<Attribute>模型传递给它。

@Model Attribute
<div class="editor-label">
    @Html.LabelFor(m => m.Key)
</div>

<div class="editor-field">
    @Html.EditorFor(m => m.Value)
    @Html.ValidationMessageFor(m => item.Value)
</div>

在您看来使用:

<fieldset>
    @Html.EditorFor(m > m)

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

您需要这样做,因为foreach不会为元素创建正确的名称。

于 2012-12-12T19:49:35.673 回答