试用EditForm

根据blazor server 自动生成的例子

 

@page "/fetchdata"

<PageTitle>Weather forecast</PageTitle>

@using BlazorApp5.Data
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
<input type="number" width="2" min="0" max="@upperIndex" @onchange="ChangeForecast" value="@index" />

<EditForm Model=@currentForecast>
<InputDate @bind-Value=currentForecast.Date></InputDate>
<InputNumber @bind-Value=currentForecast.TemperatureC></InputNumber>
<InputText @bind-Value=currentForecast.Summary></InputText>
</EditForm>
@code {
private WeatherForecast[]? forecasts;
private WeatherForecast currentForecast;
private int index = 0;
private int upperIndex = 0;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
currentForecast = forecasts[index];
upperIndex = forecasts.Count() - 1;
}
private async Task ChangeForecast(ChangeEventArgs e)
{
index = int.Parse(e.Value as string);
if (index <= upperIndex && index >= 0)
{
currentForecast = forecasts[index];
}
}
}

在此示例中,OnInitialized 事件使用外部服务填充 WeatherForecast 对象数组。 currentForecast 变量设置为数组中的第一个项;这是由 EditForm 显示的对象。 用户可以使用页面上 EditForm 上方的数值输入域在数组中循环。 将此字段的值用作数组的索引,并使用 ChangeForecast 方法将 currentForecast 变量设置为在该索引处找到的对象。

 

EditForm 使用 EditContext 对象跟踪作为模型的当前对象的状态,包括哪些字段已更改及其当前值。 提交事件作为参数传递此 EditContext 对象。

  • 在 EditForm 组件中,添加 DataAnnotationsValidator 组件,它将根据用户输入的值检查模型注释。
  • 如果希望在提交的表单中显示所有验证消息的摘要,请使用 ValidationSummary 组件。
  • 如果要显示特定模型属性的验证消息,请使用 ValidationMessage 组件。
  • 可以在模型中使用的其他注释包括:

    • [ValidationNever]:如果要确保该字段从不包含在验证中,请使用此注释。
    • [CreditCard]:如果要记录用户的有效信用卡号,请使用此注释。
    • [Compare]:如果要确保模型中的两个属性匹配,请使用此注释。
    • [Phone]:如果要记录用户的有效电话号码,请使用此注释。
    • [RegularExpression]:如果通过将值与正则表达式进行比较来检查值的格式,请使用此注释。
    • [StringLength]:如果要检查字符串值的长度是否不超过最大长度,请使用此注释。
    • [Url]:如果要记录用户的有效 URL,请使用此注释。
posted @ 2024-03-29 16:44  Biyuanguang  阅读(3)  评论(0编辑  收藏  举报