在Asp.Net Core 3.0中,自定义控件验证可能不起作用的原因是因为验证器没有正确配置或未正确应用到控件上。以下是一个可能的解决方法,包含代码示例:
// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// 添加验证服务
services.AddRazorPages().AddMvcOptions(options =>
{
options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(x => "该字段不能为空。");
}).AddViewLocalization();
// 添加自定义验证器
services.AddSingleton();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// 省略其他配置代码
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
// CustomValidator.cs
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
public class CustomValidator : IValidator
{
public IEnumerable Validate(ModelValidationContext context)
{
// 自定义验证逻辑
if (context.ModelMetadata.PropertyName == "MyProperty")
{
var value = context.Model as string;
if (string.IsNullOrEmpty(value))
{
yield return new ModelValidationResult(context.ModelMetadata.PropertyName, "该字段不能为空。");
}
}
}
}
// Index.cshtml
@model MyViewModel
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
// HomeController.cs
using Microsoft.AspNetCore.Mvc;
public class HomeController : Controller
{
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// 处理表单提交逻辑
return RedirectToAction("Success");
}
}
public class MyViewModel
{
[Required(ErrorMessage = "该字段不能为空。")]
public string MyProperty { get; set; }
}
通过以上步骤,你可以自定义控件验证生效,并在表单提交时进行验证。如果自定义验证仍然不起作用,可以检查是否添加了正确的引用、命名空间和所需的依赖项。
上一篇:ASP.NET Core 3.0自定义错误页面不可访问
下一篇:ASP.NET Core 3.0,如何将带有用户信息列表的Enumerable从控制器传递到_layout页面(.cshtml)?