我正在 Blazor HTML 部分中执行类似的操作...
<EditForm EditContext="editContext" OnValidSubmit="SubmitQuery">
<DataAnnotationsValidator />
<Microsoft.AspNetCore.Components.Forms.ValidationSummary />
<InputRadioGroup @bind-Value="@Model.Selection">
<InputRadio Value="FindGuestDisplay.Selections[0]" /><label>@(FindGuestDisplay.Selections[0]):</label>
<br />
<label class="fglabel">First Name:</label><InputText @bind-Value="@FirstName" style="width:300px" />
<label class="fglabel">Last Name:</label><InputText @bind-Value="@LastName" style="width:300px" />
...
在代码部分中,我将模型设置器包装在本地属性中,如下所示......
private string FirstName { get { return Model!.FirstName ?? ""; } set { Model!.FirstName = value; } }
private string LastName { get { return Model!.LastName ?? ""; } set { Model.LastName = value; } }
我这样做是因为如果我直接使用模型属性,我会在整个代码中收到错误,这将警告限制为仅对设置器进行。
请注意,此代码有效,但我想以正确的方式执行此操作,无需发出警告。 顺便说一句,我所做的几乎完全按照微软使用编辑表单的示例所述的方式进行,那么我怎样才能摆脱这个错误呢?我应该使用合适的替代方案吗?
这是我的 Blazor 组件中的模型声明(未设置或从外部传入):
FindGuestDisplay Model { get; set; }= new ();
模型在此处传递到 editContext 中:
protected override void OnInitialized()
{
editContext = new(Model);
editContext.OnValidationRequested += HandleValidationRequested;
messageStore = new(editContext);
}
这是我的类定义:
public class FindGuestDisplay
{
[Parameter]
[StringLength(50, ErrorMessage = "Email is too long.")]
public string Email { get; set; } = "";
[Parameter]
//[Required]
[StringLength(15, ErrorMessage = "First Name is too long.")]
public string FirstName { get; set; } = "";
[Parameter]
[StringLength(25, ErrorMessage = "Last Name is too long.")]
public string LastName { get; set; } = "";
[Parameter]
[StringLength(15, ErrorMessage = "Cell Phone is too long.")]
public string CellPhone { get; set; } = "";
[Parameter]
[StringLength(15, ErrorMessage = "Home Phone is too long.")]
public string HomePhone { get; set; } = "";
[Parameter]
[StringLength(25, ErrorMessage = "Work Phone is too long.")]
public string WorkPhone { get; set; } = "";
[Parameter]
[StringLength(50, ErrorMessage = "Business Name is too long.")]
public string BusinessName { get; set; } = "";
[Parameter]
public string? BarcodeID { get; set; }
public string Selection { get; set; } = "Enter Guest Information";
public static readonly List<String> Selections =
[ "Enter Guest Information", "Find Web GuestPass", "Find Business" ];
}
如有任何帮助,我们将不胜感激。谢谢!
根据我的理解,我正在以正确的方式这样做。这只是一个糟糕的警告吗?
这是我使用的模式:
@page "/mypage"
@if (Model == null)
{
return;
}
<div>First Name: @Model.FirstName</div> Model is not null here -> no warnings
@code
{
MyPageModel? Model {get; set;}
//Instantiate the model anywhere...
}
如果模型作为参数传递,我使用
required
关键字和 [EditorRequired]
:
[Parameter, EditorRequired]
public required MyPageModel {get; set;}