gpt4 book ai didi

asp.net-mvc - 使用带有 IEnumerable 的 Html.EditorFor

转载 作者:行者123 更新时间:2023-12-03 17:49:56 26 4
gpt4 key购买 nike

我有一个自定义类:

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

我将这个类传递给我的强类型 View :
<%@ 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] 不是直接属性。有没有人有办法在不使用字符串来指定控件名称的情况下使代码工作?这甚至可能吗?最佳情况下,我想使用从模型到需要编辑器的项目的表达式,它自己确定输入控件的名称。

尝试更多的东西,我能够通过对 View 进行以下更改来使其正常工作:
<% 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 中表达式的右侧必须是您尝试填充的列表的确切名称,并且该列表必须是基本类型(即 String、Int32 等)。但是,当我尝试使用复杂类型时,它仍然失败。我尝试显示此人员类的列表,其中包含每个属性的输入,并将所有这些都显示在浏览器中就好了,但随后它会向我的 post 操作返回一个空列表。如何让索引显示在列表项目的输入名称中?

This was a giant help in figuring out what was going on.

最佳答案

我假设这是用于最喜欢的食物列表。它在 ASP.NET MVC v1 中的实现方式是这样的:

<input type="hidden" name="FavouriteFoods.Index" value="0" />

关于asp.net-mvc - 使用带有 IEnumerable<T> 的 Html.EditorFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1478378/

26 4 0