使用 ContentPart 检索设置参数,将其值保存在 ContentItem 上,并更新设置参数

Using a ContentPart to retrieve a settings parameter, save it's value on a ContentItem, and updating the settings parameter

我正在尝试构建一个包含可附加到内容类型的内容部分的模块,因此当创建新的内容项时,它会从设置中检索“last id”int 参数,向其添加 1,并将其同时保存到新的内容项和设置参数中。

所以,设置参数似乎工作正常,我可以从管理菜单访问它,设置它的值并保存它。创建内容部分也很有效,我可以将该部分添加到现有的内容类型,创建一个新的内容项,当我保存它时,它会进入已注册的驱动程序的 UpdateAsync 方法。这就是一切都向南发展的时候。这是来自 ContentPart 驱动程序的 UpdateAsync 方法:

public override async Task<IDisplayResult> UpdateAsync(IncrementalPart model, IUpdateModel updater)
{
    // Create IncrementalId only doesn't exist (IncrementalId is int?)
    if (!model.IncrementalId.HasValue) 
    {
        // Retrieve site settings
        var incrementalSettings = _siteService.GetSiteSettingsAsync()
            .GetAwaiter()
            .GetResult();
        // Get last Assigned Id, increment it, and set it to the model's IncrementalId
        model.IncrementalId = ++incrementalSettings.As<IncrementalSettings>().LastId;
        // Save model
        await updater.TryUpdateModelAsync(
            model,
            Prefix,
            t => t.IncrementalId
        );
        // Update and save the last assigned Id
        incrementalSettings.Alter<IncrementalSettings>(nameof(IncrementalSettings), isett => isett.LastId = model.IncrementalId.GetValueOrDefault());
        await _siteService.UpdateSiteSettingsAsync(incrementalSettings);
    }

    return Edit(model);
}

在“编辑”视图中,这部分没有任何实际的可编辑输入,因为不应该手动编辑它,应该在第一次使用 IncrementalPart 保存内容项时创建它在它上面,并且只在那之后显示(只是一个 <p> 显示分配的编号,上面有一个 <input type="hidden" asp-for="IncrementalId" /> 以保留版本上的 ID)。

这就是我的发现。当我尝试保存 IncrementalId 字段时,它没有保存任何内容,调用 await updater.TryUpdateModelAsync 后模型的 LastId 值为空,因此在设置中保存新的 LastId 字段时失败。

另一方面,如果我尝试在使用新值更新 ContentItem 部分之前保存设置,它可以保存 LastId 值,但随后它会脱离 UpdateAsync 方法,所以我无法更新

之后的 IncrementalId 值

我做错了什么?我将这个模块建立在我之前基于一个示例制作的模块中,它只是从编辑器中保存了几个值并将它们显示在相应的内容项页面上,并且工作正常,当我添加 retrieve/save设置部分。

提前致谢。

更新:所以,我已经设法从配置中检索一个值,在模型上更新它并保存它,但是,当我尝试将最后分配的值保存回设置时,它只是破坏了执行,当 await _siteService.UpdateSiteSettingsAsync(incrementalSettings);被执行了,最后的return Edit(model);没有。

这听起来像是一个 XY 问题,尽管我认为问题在于您想要获取零件本身然后更改其上的字段。下面是我在以编程方式添加 contentItems 时使用的一些代码。

var salesPersonPart = salesPersonContentItem.As<Parts.SalesPerson>();
salesPersonPart.Alter<NumericField> (nameof(Parts.SalesPerson.SalesPersonId), field => field.Value = salesPerson.SalesPersonId.Value);

编辑: 查看源代码的其他部分,重新​​编辑。看起来像这样可以更新站点设置。

        var site = await _siteService.LoadSiteSettingsAsync();
        site.Properties["IncrementalSettings"] = IncrementalSettings.Id;
        await _siteService.UpdateSiteSettingsAsync(site);

UpdateSiteSettingsAsync 的使用分散在整个源代码中,因此请查看 Orchard Core 是如何实现的。