簡體   English   中英

使用MVC2的EditTemplates和相關對象

[英]EditTemplates and related objects with MVC2

我正在使用v2和Entity Framework v4一起學習MVC。 假設我有3個對象:游戲,積分和玩家。 它們以以下方式關聯:游戲具有點,並且點可以具有與其相關聯的玩家(1個游戲到多個點,並且一個點對象可以具有一個玩家)。

我正在嘗試使用MVC2中的EditTemplates功能來呈現我的視圖。 在“游戲編輯”視圖中,我希望可編輯基本的游戲對象信息以及相關的“點”對象。 目前,我正在使用“ <%= Html.EditorForModel() %> ”(這似乎很慢)來呈現“編輯視圖”,然后有一個特定的Game和Point EditTemplates。

數據可以正確呈現,並且對於Game和Point信息都是可編輯的。 當我去執行更新並提交表單時,我在更新ActionResult中收到“游戲”對象。 為游戲對象填充了基本屬性,但沒有任何深層屬性(例如,點); 它們顯示為空。 如果我在調試中查看Request.Form變量,則可以看到Points字段正在傳遞給服務器,但沒有將其放回Game對象中。

在我的游戲EditTemplate中,我使用以下方法渲染Points對象:

<%= Html.EditorFor(c => c.Points) %>

我的積分EditTemplate看起來像:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Domain.Model.Entities.Point>" %>

<%= Html.EditorFor(c => c.PntId)%>
<tr><td><%= Html.DisplayFor(c => c.User.Username)%></td><td><%= Html.EditorFor(c => c.UserPnt)%></td></tr>

我呈現的HTML如下所示:

<input id="Points_Points_0__PntId" name="Points.Points[0].PntId" type="hidden" value="226" />
<tr><td>Jay</td><td><input class="text-box single-line" id="Points_Points_0__UserPnts" name="Points.Points[0].UserPnts" type="text" value="20" /></td></tr>

<input id="Points_Points_1__PntId" name="Points.Points[1].PntId" type="hidden" value="227" />
<tr><td>Joe</td><td><input class="text-box single-line" id="Points_Points_1__UserPnts" name="Points.Points[1].UserPnts" type="text" value="20" /></td></tr>

如何獲取深層的屬性,以發布回Controller Update ActionResult接受的Game對象中,以便同時更新它們?

更新:這顯然與EditTemplate渲染Points集合的方式有關。 如果我手動將以下內容添加到視圖,則它確實會正確顯示在Game對象中:

<input class="text-box single-line" id="Game_Points_0__UserPnts" name="Game.Points[0].UserPnts" type="text" value="20" />
        <input class="text-box single-line" id="Game_Points_1__UserPnts" name="Game.Points[1].UserPnts" type="text" value="20" />

知道為什么將其渲染為“ Points.Points [index]而不是Game.Points [index]嗎?我試圖弄亂EditFor中的參數:

<%= Html.EditorFor(c => c.Points,null,"Game.Points") %>

但隨后輸入呈現為Game.Points.Game.Points [index]

這顯然是MVC早期版本中的錯誤。 根據我在MVC論壇上從Microsoft收到的評論,它似乎已在RTM版本中修復。

同時,我又回到了使用for循環來生成HTML的過程。

這是MVC論壇的響應,以供參考: http : //forums.asp.net/t/1515461.aspx

它們必須被命名為Game.Points [0] .PntId,或者您可以將Points添加為您的操作的參數,然后將它們組合起來。 特別是如果要將它們持久存儲在數據庫中,則必須附加它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM