我是数据注释和Fluent API的新手,
MVC中的数据注释和Fluent API是否可以同时在客户端和服务器端进行验证?
如果是,如何在两者中同时使用它们?我应该在哪一边使用它们?
例如,是否应该仅在服务器端使用Fluent API,依此类推??
是的,同时进行客户端和服务器端的验证! Install FormHelper from Nuget.
您可以检查github页面的用法:https://github.com/sinanbozkus/FormHelper
Form Helper可帮助您创建ajax表单和验证,而无需编写任何javascript代码。它将服务器端验证转换为客户端端。您也可以使用不带ajax的表单验证器。
与Fluent验证兼容(您可以将客户端验证支持添加到Fluent验证。)
安装
可以使用Nuget软件包管理器或dotnet CLI安装FormHelper。
包管理器:
Install-Package FormHelper
dotnet CLI:
dotnet add package FormHelper
此库取决于某些软件包:
jQuery验证不引人注目烤面包机CDN:
// css
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" />
// js
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<!-- form helper - You don't need to add this file to your project, just add it. it's embeded! -->
<script src="/formhelper/formhelper.min.js"></script>
用法Startup.cs
ConfigureServices:
services.AddFormHelper();
With configuration: (optional)
services.AddFormHelper(new FormHelperConfiguration
{
CheckTheFormFieldsMessage = "Your custom message...",
RedirectDelay = 6000
});
配置:
<!-- If you want to use embeded form helper script file, add this line -->
app.UseFormHelper();
ViewImports.cshtml
@using FormHelper
@addTagHelper *, FormHelper
View: (TagHelper)
<form asp-formhelper="true" asp-controller="Home" asp-action="Save">
// <input...
// ...
</form>
// You can use <form asp-formhelper="true"> or <formhelper> to activate formhelper.
// Optional parameters:
// asp-callback="...", asp-beforeSubmit="...", asp-dataType="FormData/Json", asp-enableButtonAfterSuccess="False"
Controller:
[HttpPost, FormValidator]
public IActionResult Save(FormViewModel viewModel)
// If you use Json data type, you need to add [FromBody] attribute.
// public IActionResult Save([FromBody]FormViewModel viewModel)
从控制器返回结果:
错误消息:
return FormResult.CreateErrorResult("An error occured.");
成功消息:
return FormResult.CreateSuccessResult("Product saved.");
成功重定向消息:
return FormResult.CreateSuccessResult("Product saved. Please wait...", Url.Action("Home", "Index"));
具有重定向和延迟时间的成功消息:
return FormResult.CreateSuccessResult("Product saved. Please wait...", Url.Action("Home", "Index"), 10000); // 10 seconds