我正在使用我的UserProfile編輯器,並且我正在使用EditorTemplates,但我無法弄清楚使用此方法爲複雜對象提交數據的正確方法。我不知道我是否有正確的觀點,以及如何從所有部分視圖中捲起複雜的對象。爲了簡化,我將稍微削減一下,但是我的UserProfile有許多代表用戶偏好的子對象。從MVC5的EditorTemplates提交複雜數據的正確方法
CREATE TABLE [dbo].[UserProfile] (
[UserProfileId] INT IDENTITY (1, 1) NOT NULL,
[NickName] VARCHAR (MAX) NOT NULL,
[ThumbnailImageId] INT NULL,
);
在我的實體,我有導航的對象,其指向ThumbnailImage對象,所以在我EditorTemplate(對於用戶配置),我可以這樣做:
<div class="form-group">
@Html.LabelFor(model => model.NickName, htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.NickName, new { htmlAttributes = new { @class = "form-control" } })
</div>
<div class="form-group">
@Html.LabelFor(model => model.ThumbnailImage, "ThumbnailImage", htmlAttributes: new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.ThumbnailImage, new { @class = "form-control" })
</div>
注意,第二EditorFor是ThumbnailImage對象,而不是ID。我有一個EditorTemplate的對象,但我不確定哪種編碼方式是最好的。我知道如何做到這一點,我只是在尋找可以選擇的方式。如果有這樣的「最佳做法」,請讓我知道。
選項1 - 「手動」在UserProfile視圖中彙總頂層對象。對於此選項,我將在UserProfile視圖中進行Ajax調用,該視圖提交整個對象,包括使用JQuery使用HTML元素ID的前綴從ThumbnailImage編輯器抓取的ThumbnailImageId。所以,我的提交按鈕會住在用戶配置EditorTemplate,其作用是這樣的......(除了將生成的URL和元素ID)
var NickName = $('#MyNickNameId').val();
var ThumbnailImageId = $('#ImageEditorId').val();
$.ajax({
url: '/Account/UserProfile',
contentType: 'application/html; charset=utf-8',
data: {
UserProfileId: idVal,
NickName: NickName,
ThumbnailImageId: ThumbnailImageId
}
});
選項2 - 立即編輯子對象,並且不要在頂層視圖中提交它們。在這個選項中,我的ThumbnailImage編輯器會使用Ajax立即更新數據庫,通過保存圖像數據本身,然後使用ID更新父對象(如果它已更改)。這樣,當用戶提交頂級UserProfile編輯器時,它只會提交NickName,並且任何對子對象的更新都已完成。我喜歡這個選項以獲得流暢的UI原因,但我可以讓選項1對用戶來說也很流暢。
選項3 - 與子對象的EditorTemplates(ThumbnailImage)不要走,並在父編輯(用戶配置)查看 - 這意味着我將有觀點的重複代碼,但因爲其他的事情都會有ThumbnailImage對象,而不僅僅是用戶配置文件。在一個視圖中使整個對象更簡單一些,但我並沒有在這方面看到任何優勢(但是,這是我們在工作中所做的,我們不使用模型綁定)
如何繪製取決於哪個選項,還是有更好的選擇,我不考慮?
目前我正在做選項1.它可以工作,但是它有很多代碼並且不能很好地重用。