我正在创建一个调查生成器,其主Razor页面名为Survey
,然后从这里添加调查元素。如果我从代码创建调查,则组件正在工作。每个组件都使用HTML标记,如
@inherits ElementBase<string>
<input type="@ElementData.TextboxType.GetDescription()"
name="@Name" placeholder="@ElementData.PlaceHolder"
@bind-value="@Value" class="form-control @CssInternal @CssClass">
所有自定义组件都是从实现
[CascadingParameter] internal EditContext ElementEditContext { get; set; }
[CascadingParameter] internal Survey _survey { get; set; }
private FieldIdentifier _fieldIdentifier;
[Parameter]
public T Value
{
get
{
return _value;
}
set
{
_value = value;
_survey.SetElementValue(Name, _value);
}
}
[Parameter] public EventCallback<T> ValueChanged { get; set; }
[Parameter] public Expression<Func<T>> ValueExpression { get; set; }
protected override Task OnInitializedAsync()
{
if (ElementEditContext != null)
{
// omitted for simplicity
ElementEditContext.OnFieldChanged += FieldChanged;
ElementEditContext.OnValidationRequested += ValidationRequested;
}
_survey.ElementValuesChanged += SurveyGenerator_ElementValuesChanged;
return Task.CompletedTask;
}
在Survey
页面中
<CascadingValue Value="this">
<EditForm EditContext="@editContext" OnValidSubmit="@ValidFormSubmitted">
<table class="table">
<tbody>
@for (int i = 0; i < Form.Elements.Count(); i++)
{
<tr>
<td>
<SurveyFieldGenerator
Element="@Form.Elements[i]" />
</td>
</tr>
}
@if (ChildContent != null)
{
@ChildContent
}
<tr>
<td colspan="2">
<button class="btn btn-primary"
@onclick="Submit">Submit</button>
</td>
</tr>
</tbody>
</table>
</EditForm>
</CascadingValue>
现在,我尝试使用一些组件,但是从Razor页面添加了以下代码
<Survey ShowDebug="true">
<Survey.Components.Checkbox ElementData="@config" />
</Survey>
在这里,我得到了一个错误:
Unhandled exception rendering component: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.
System.InvalidOperationException: EditForm requires either a Model parameter, or an EditContext parameter, please provide one of these.
at Microsoft.AspNetCore.Components.Forms.EditForm.OnParametersSet()
at Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync()
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
我读了文档从零开始为Blazor创建Bespoke输入组件和在堆栈溢出上张贴。
首先,在OnInitialized
中会立即引发一个错误,因为ValueExpression
是null
。
protected override void OnInitialized()
{
_fieldIdentifier = FieldIdentifier.Create(ValueExpression);
}
因此,如何更改组件或只更改基类以解决此问题?
发布于 2022-08-31 14:32:01
您的代码没有显示Survery页面的变量editContext以及它是如何创建的。
但是,正如Shaun所指出的,该错误表明该变量在第一次呈现页面时为null。
在Survey标记中尝试使用以下方法获得可见性:
@if (editContext == null)
{
<div>editContext is null !!!!</div>
}
else
{
<EditForm EditContext="@editContext">
@* Form Context *@
</EditForm>
}
https://stackoverflow.com/questions/73555837
复制相似问题