【发布时间】:2019-08-02 06:41:43
【问题描述】:
我正在使用 .NET Core 2.0 编写应用程序。我想用数据注释控制输入元素。
在模型端,我使用了数据注释,在 UI 端,我使用了 asp-validation-for 标签助手。代码如下。
在模型类中;
namespace ExampleApp
{
public class UserViewModel
{
[Required(ErrorMessage="Please fill this field"),
Display(Name="Your Name:")]
public string Firstname { get; set; }
[Required(ErrorMessage = "Please fill this field")]
public string Lastname { get; set; }
}
}
在文件UserAdd.cshtml:
@model UserViewModel
<div class="form-group">
<label class="control-label mb-10">First name</label>
<input asp-for="@Model.Firstname" class="form-control">
<span asp-validation-for="@Model.Firstname" class="text-danger">
</span>
</div>
<div class="form-group">
<label class="control-label mb-10">Soyadı</label>
<input asp-for="@Model.Lastname" class="form-control">
<span asp-validation-for="@Model.Lastname" class="text-danger">
</span>
</div>
在 Startup.cs 文件中配置方法;
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在我的控制器端;
当我单击带有空输入值的提交按钮时,模型的 Isvalid 值等于 false。但是UI页面上没有任何错误信息。
为什么用户界面中没有显示错误消息,我的错在哪里?
【问题讨论】:
-
所以你有一个无效的模型
server-side,但你想显示错误client-side? -
asp-validation-for="Firstname" -
@JohnB 是的,当然!
标签: c# asp.net-core asp.net-core-2.0 data-annotations