【发布时间】:2021-08-15 01:55:57
【问题描述】:
【问题讨论】:
标签: kentico kentico-12 kentico-mvc
【问题讨论】:
标签: kentico kentico-12 kentico-mvc
在 Kentico 12 MVC 中,无法在另一个小部件中呈现表单小部件。
您需要升级到 Kentico Xperience 13 才能使用此功能 - 请参阅 https://docs.xperience.io/developing-websites/page-builder-development/rendering-widgets-in-code#Renderingwidgetsincode-Renderingwidgets
【讨论】:
从技术上讲,您可以在 Kentico 12 中的 Widget 中呈现表单,但它不受官方支持,需要一些自定义开发。
关键是使用IFormProvider 和IFormComponentVisibilityEvaluator 获取所有表单信息,以便您可以手动呈现(在控制器中):
var formInfo = BizFormInfoProvider
.GetBizFormInfo(formName, SiteContext.CurrentSiteName);
string className = DataClassInfoProvider
.GetClassName(formInfo.FormClassID);
var existingBizFormItem = className is null
? null
: BizFormItemProvider
.GetItems(className)?.GetExistingItemForContact(
formInfo, contactContext.ContactGuid);
var formComponents = formProvider
.GetFormComponents(formInfo)
.GetDisplayedComponents(
ContactManagementContext.CurrentContact,
formInfo, existingBizFormItem, visibilityEvaluator);
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
TypeNameHandling = TypeNameHandling.Auto,
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var formConfiguration = JsonConvert.DeserializeObject<FormBuilderConfiguration>(
formInfo.FormBuilderLayout, settings);
var prefix = Guid.NewGuid().ToString();
ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
return new FormWidgetViewModel
{
DisplayValidationErrors = true,
FormComponents = formComponents.ToList(),
FormConfiguration = formConfiguration,
FormName = formName,
FormPrefix = prefix,
IsFormSubmittable = true,
SiteForms = new List<SelectListItem>(),
SubmitButtonImage = formInfo.FormSubmitButtonImage,
SubmitButtonText = string.IsNullOrEmpty(formInfo.FormSubmitButtonText)
? ResHelper.GetString("general.submit")
: ResHelper.LocalizeString(formInfo.FormSubmitButtonText)
};
然后您将使用 Kentico 的表单呈现 API 将表单模型呈现为 HTML 表单:
<!-- ~/Views/Form/Form.cshtml -->
@using Kentico.Forms.Web.Mvc;
@using Kentico.Forms.Web.Mvc.Widgets;
@using Kentico.Forms.Web.Mvc.Widgets.Internal
@model FormWidgetViewModel
@{
var config = FormWidgetRenderingConfiguration.Default;
// @Html.Kentico().FormSubmitButton(Model) requires
// this ViewData value to be populated. Normally it
// executes as part of the Widget rendering, but since
// we aren't rendering a Widget, we have to do it manually
ViewData.AddFormWidgetRenderingConfiguration(config);
}
@using (Html.Kentico().BeginForm(Model))
{
@Html.Kentico().FormFields(Model)
@Html.Kentico().FormSubmitButton(Model)
}
您可以在我的博文 Kentico EMS: MVC Widget Experiments Part 3 - Rendering Form Builder Forms Without Widgets 中了解完整的配置和设置
【讨论】: