【发布时间】:2015-07-03 08:39:41
【问题描述】:
我正在使用我的 UserProfile 编辑器并为此使用 EditorTemplates,但我无法找到使用此方法为复杂对象提交数据的正确方法。我不知道我是否有正确的视图,以及如何从所有部分视图中汇总复杂对象。为简化起见,我将把它减少一点,但我的 UserProfile 有许多代表用户偏好的子对象。
CREATE TABLE [dbo].[UserProfile] (
[UserProfileId] INT IDENTITY (1, 1) NOT NULL,
[NickName] VARCHAR (MAX) NOT NULL,
[ThumbnailImageId] INT NULL,
);
在我的实体中,我有指向 ThumbnailImage 对象的导航对象,所以在我的 EditorTemplate(对于 UserProfile)中我可以这样做:
<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 调用,它会提交整个对象,包括ThumbnailImageId 它将使用 HTML 元素 ID 的前缀从带有 JQuery 的 ThumbnailImage 编辑器中获取。因此,我的提交按钮将位于 UserProfile 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 - 取消子对象 (ThumbnailImage) 的 EditorTemplates 并在父 (UserProfile) 视图中编辑它们 - 这意味着我将在视图中有重复的代码,因为其他事物将具有 ThumbnailImage 对象,而不仅仅是用户配置文件。将整个对象放在一个视图中稍微简单一些,但我并没有真正看到这样做的任何优势(但是,这是我们在工作中所做的,我们不使用模型绑定)
我如何确定要使用哪个选项,或者是否有更好的选项我没有考虑?
目前我正在做选项 1。它可以工作,但它的代码很多,而且不可重复使用。
【问题讨论】:
标签: ajax asp.net-mvc-5