如果我告诉你“你需要太阳镜或雨伞,但不是两者都需要。”你不知道是否下雨。运行我的 Blazor Web 应用程序时,我得到
<块引用>EditForm 需要一个 Model 参数,或者一个 EditContext 参数,但不是两者都需要
我的代码有:
<EditForm Model="@order" OnSubmit="OnSubmit">
据我所知,我只使用模型参数。我认为应该禁止在错误消息中使用“或”这个词。我的猜测是某些东西自动生成了 EditContext。有人知道去哪里看吗?
答案 0 :(得分:3)
要为 Eric 的回答添加更多细节,EditForm
中生成违规消息的相关代码部分是:
private bool _hasSetEditContextExplicitly;
[Parameter] public object? Model { get; set; }
[Parameter]
public EditContext? EditContext
{
get => _editContext;
set
{
_editContext = value;
_hasSetEditContextExplicitly = value != null;
}
}
和覆盖的 OnParametersSet
,如果未明确设置,它会尝试获取 Editcontext
。第一个 else if
抛出了您的错误,因此 Model
必须为空!
protected override void OnParametersSet()
{
if (_hasSetEditContextExplicitly && Model != null)
{
throw new InvalidOperationException($"{nameof(EditForm)} requires a {nameof(Model)} " +
$"parameter, or an {nameof(EditContext)} parameter, but not both.");
}
else if (!_hasSetEditContextExplicitly && Model == null)
{
throw new InvalidOperationException($"{nameof(EditForm)} requires either a {nameof(Model)} " +
$"parameter, or an {nameof(EditContext)} parameter, please provide one of these.");
}
// If you're using OnSubmit, it becomes your responsibility to trigger validation manually
// (e.g., so you can display a "pending" state in the UI). In that case you don't want the
// system to trigger a second validation implicitly, so don't combine it with the simplified
// OnValidSubmit/OnInvalidSubmit handlers.
if (OnSubmit.HasDelegate && (OnValidSubmit.HasDelegate || OnInvalidSubmit.HasDelegate))
{
throw new InvalidOperationException($"When supplying an {nameof(OnSubmit)} parameter to " +
$"{nameof(EditForm)}, do not also supply {nameof(OnValidSubmit)} or {nameof(OnInvalidSubmit)}.");
}
// Update _editContext if we don't have one yet, or if they are supplying a
// potentially new EditContext, or if they are supplying a different Model
if (Model != null && Model != _editContext?.Model)
{
_editContext = new EditContext(Model!);
}
}
完整的EditForm
代码是here
答案 1 :(得分:2)
您是否为变量 @order
创建了一个实例?如果您定义了 @order
但将其保留为空,您将收到此错误消息。
如果是这种情况,它与公认的尴尬错误消息有关,因为“EditForm 需要一个 Model 参数或一个 EditContext 参数”,但您两者都没有提供。
见:ASP.NET Core Blazor forms and validation : Troubleshoot
<块引用>给表单分配Model时,确认模型类型已经实例化
答案 2 :(得分:0)
我在使用异步操作构建模型时遇到了类似的错误
<块引用>System.InvalidOperationException: EditForm 需要一个模型 参数或 EditContext 参数,请提供其中之一。
模型还没有完全准备好。我通过测试 null 并显示微调器来解决它。等待时间很短,但需要等待。
@if (myModel == null)
{
<div class="spinner"></div>
}
else
{
<EditForm Model="@myModel">
...
}