我有一个自定义类:

public class Person
{
    public String Name { get; set; }
    public Int32 Age { get; set; }
    public List<String> FavoriteFoods { get; set; }

    public Person()
    {
        this.FavoriteFoods = new List<String>();
        this.FavoriteFoods.Add("Jambalya");
    }
}

我将此类传递给我的强类型视图:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcLearner.Models.Person>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
 Create
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Create</h2>

    <% using (Html.BeginForm()) { %>
        <%= Html.LabelFor(person => person.Name) %><br />
        <%= Html.EditorFor(person => person.Name) %><br />
        <%= Html.LabelFor(person => person.Age) %><br />
        <%= Html.EditorFor(person => person.Age) %><br />
        <%= Html.LabelFor(person => person.FavoriteFoods[0]) %><br />
        <%= Html.EditorFor(person => person.FavoriteFoods[0]) %>
    <% } %>

</asp:Content>

当我浏览该页面时,最终出现错误消息:模板只能与字段和属性访问器表达式一起使用。经过一番谷歌搜索后,我发现发生这种情况是因为 EditorFor 和 LabelFor 函数只能接受 Model 对象的直接属性,而FavoriteFoods[0] 不是直接属性。有没有人有办法让代码在不使用字符串指定控件名称的情况下工作?这可能吗?最好我想使用从模型到需要编辑器的项目的表达式,该表达式自行确定输入控件的名称。

尝试更多的事情,我能够使用对视图的以下更改来使其工作:

<% using (Html.BeginForm()) { %>
    <%= Html.LabelFor(person => person.Name) %><br />
    <%= Html.EditorFor(person => person.Name) %><br />
    <%= Html.LabelFor(person => person.Age) %><br />
    <%= Html.EditorFor(person => person.Age) %><br />
    <% foreach (String FavoriteFoods in Model.FavoriteFoods) { %>
        <%= Html.LabelFor(food => FavoriteFoods) %><br />
        <%= Html.EditorFor(food => FavoriteFoods)%><br />
    <% } %>
    <input type="submit" value="Submit" />
<% } %>

但值得注意的是,EditorFor 和 LabelFor 中表达式的右侧必须是您尝试填充的列表的确切名称,并且该列表必须是基本类型(即字符串、Int32 等)。然而,当我尝试使用复杂类型时,它仍然失败。我尝试显示此 person 类的列表,其中包含每个属性的输入,并且它将所有这些都很好地显示到浏览器,但随后它向我的发布操作返回一个空列表。如何让索引显示在列表项的输入名称中?

这对于弄清楚正在发生的事情有很大帮助。

有帮助吗?

解决方案

我假定这是为FavoriteFoods列表。它是如何在ASP.NET MVC V1已经做了有这样的事情:

<input type="hidden" name="FavouriteFoods.Index" value="0" />
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top