asp.net-mvc - 为什么我的 http 帖子从我的 View 模型返回 null

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-2 asp.net-mvc-4 asp.net-mvc-viewmodel

这是我的模型:

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);
    }

我的 View 如下所示:

@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一片空白。有什么建议吗?

最佳答案

您需要为 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没有为元素创建正确的名称。

关于asp.net-mvc - 为什么我的 http 帖子从我的 View 模型返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13847379/

相关文章:

asp.net - 使用 MVC 4.0 的 DotNetOpenAuth

asp.net-mvc-2 - TDD使用ASP.NET MVC 2,NUnit和Rhino Mocks的 Controller

c# - MVC Razor 隐藏输入和传递值

c# - 通读流阅读器并使用行中的一些文本

asp.net-mvc-2 - 第一次单击复选框时 jquery live 不会触发

asp.net - 有哪些选项可用于在 ASP.NET MVC2 中存储应用程序设置?

asp.net-mvc - ASP.Net MVC TempData - 如何保持状态

ASP.NET MVP 作为 ASP.NET Webforms 和 ASP.NET MVC 的共生体

c# - 对象不是响应消息模型的原语

asp.net-mvc-3 - 使用 ASP.NET 成员(member)提供程序从 MVC3 站点进行 TNS oracle 连接失败