我试图遵循从youtube频道创建表单的说明,例如: https://www.youtube.com/watch?v=zfqQ_fhmPOQ 要么 https://www.youtube.com/watch?v=40njRXr6eUo 甚至我尝试过这样的非常简单的代码
<EditForm Model="@author" OnValidSubmit="SaveAuthor">
<p>
<label></label>
<InputText id="FirstName" @bind-Value="author.FirstName"/>
</p>
</EditForm>
这是我的代码示例https://github.com/maxrena/BlazorServerApp.git的github链接 它仍然返回这样的错误 请帮帮我。
答案 0 :(得分:7)
这是罪魁祸首:
if ((EditContext == null) == (Model == null))
{
throw new InvalidOperationException($"{nameof(EditForm)} requires a {nameof(Model)} " +
$"parameter, or an {nameof(EditContext)} parameter, but not both.");
}
您没有实例化模型,并且没有EditContext
您可能已经这样做了:Author author;
您应按以下步骤实例化对象:
您可以执行以下操作:
@code {
Author author = new Author();
public class Author
{
public string FirstName {get; set;} = "Charls";
}
}
运行示例:
<EditForm Model="@author" OnValidSubmit="SaveAuthor">
<p>
<label></label>
<InputText id="FirstName" @bind-Value="author.FirstName" />
</p>
<p><button type="submit">Submit</button></p>
</EditForm>
@code {
Author author = new Author();
private void SaveAuthor()
{
Console.WriteLine(author.FirstName);
}
public class Author
{
public string FirstName { get; set; } = "Charls";
}
}
希望这对您有帮助...
答案 1 :(得分:2)
要在不触发异常的情况下启用服务器加载数据,您可以使用以下代码:
@if (author== null)
{
<p><em>Loading...</em></p>
}
else
{
<EditForm Model="@author">
....
</EditForm>
``