我有一個自定義類:使用Html.EditorFor有一個IEnumerable <T>
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功能只能接受模型對象的直接屬性,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等)。但是,當我嘗試使用複雜類型時,它仍然失敗。我試圖顯示這個人的類與每個屬性的輸入列表並顯示他們都在瀏覽器就好了,但後來它返回一個空列表,以我的職務行爲。如何讓索引顯示在列表項目的輸入名稱中?
This was a giant help in figuring out what was going on.
您是否必須在MVC 1中重建控制器中的類?我想對於由框架構成的類如果可能的話,只是提供我的控制器與打包類的工作。 – 2009-09-25 19:33:11
它爲你做。我認爲,這個解決方案預示着回到菲爾哈克的帖子 - http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx – 2009-09-25 21:08:07
非常感謝該鏈接。它看起來像我的時間寫一些輔助方法到我的圖書館。 – 2009-09-25 21:22:52