试用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,请使用此注释。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!