From b69615ebabf0ff14a586d9aefc7b9ae47a452e24 Mon Sep 17 00:00:00 2001 From: ofturhan Date: Wed, 6 Nov 2024 21:50:28 +0300 Subject: [PATCH] asp-checkTheFormFieldsMessage option added and error messages are returned as html encoded --- README.md | 5 +- .../Views/Home/TagHelper.cshtml | 147 +++++----- src/FormHelper/Attributes/FormValidator.cs | 253 +++++++++--------- src/FormHelper/TagHelpers/FormTagHelper.cs | 8 +- 4 files changed, 210 insertions(+), 203 deletions(-) diff --git a/README.md b/README.md index 2e68daa..32f53d9 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,10 @@ app.UseFormHelper(); // You can use
or to activate formhelper. // Optional parameters: -// asp-callback="javascriptFunctionName", asp-beforeSubmit="javascriptFunctionName", asp-dataType="FormData/Json", asp-enableButtonAfterSuccess="false", asp-resetFormAfterSuccess="true" asp-toastrPosition="ToastrPosition.BottomRight" +// asp-callback="javascriptFunctionName", asp-beforeSubmit="javascriptFunctionName", +// asp-dataType="FormData/Json", asp-enableButtonAfterSuccess="false", +// asp-resetFormAfterSuccess="true" asp-toastrPosition="ToastrPosition.BottomRight" +// asp-checkTheFormFieldsMessage="Error message from tag helper!" ``` **Controller:** diff --git a/sample/FormHelper.Samples/Views/Home/TagHelper.cshtml b/sample/FormHelper.Samples/Views/Home/TagHelper.cshtml index deb599c..8c3dff9 100755 --- a/sample/FormHelper.Samples/Views/Home/TagHelper.cshtml +++ b/sample/FormHelper.Samples/Views/Home/TagHelper.cshtml @@ -1,86 +1,87 @@ @{ - ViewData["page"] = Page.TagHelper; + ViewData["page"] = Page.TagHelper; } @model ProductFormViewModel
-
-
-
-
- @(Model.IsNew ? "New Product" : "Edit Product") -
-
- - +
+
+
+
+ @(Model.IsNew ? "New Product" : "Edit Product") +
+
+ + - + -
- - - -
-
- - - -
-
- - - -
-
- - - -
-
- - - - - - - - - -
-
- - - -
-
-
- - -
- -
-
-
-
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + + + + + + + +
+
+ + + +
+
+
+ + +
+ +
+
+
+
@section Scripts { - + } \ No newline at end of file diff --git a/src/FormHelper/Attributes/FormValidator.cs b/src/FormHelper/Attributes/FormValidator.cs index 601b4c3..41bc741 100644 --- a/src/FormHelper/Attributes/FormValidator.cs +++ b/src/FormHelper/Attributes/FormValidator.cs @@ -8,135 +8,136 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Text; using System.Threading.Tasks; namespace FormHelper { - [AttributeUsage(AttributeTargets.Method)] - public class FormValidator : ActionFilterAttribute - { - public bool ValidateAntiforgeryToken { get; set; } = true; - public bool UseAjax { get; set; } = true; - public string ViewName { get; set; } - - - public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) - { - var httpContext = context.HttpContext; - - var antiForgery = httpContext.RequestServices.GetService(); - if (ValidateAntiforgeryToken) - { - await antiForgery.ValidateRequestAsync(httpContext); - } - - await base.OnActionExecutionAsync(context, next); - } - - public override void OnActionExecuting(ActionExecutingContext context) - { - var httpContext = context.HttpContext; - var modelState = context.ModelState; - - - if (UseAjax) - { - if (!httpContext.Request.IsAjaxRequest()) - { - context.Result = new ContentResult() - { - Content = "The request is not in the expected format. Check jQuery is loaded!", - StatusCode = StatusCodes.Status400BadRequest - }; - - return; - } - - if (!modelState.IsValid) - { - var errorModel = - from x in modelState.Keys - where modelState[x].Errors.Count > 0 - select new - { - key = x, - errors = modelState[x].Errors. - Select(y => y.ErrorMessage). - ToArray() - }; - - var formResult = new FormResult(FormResultStatus.Error) - { - ValidationErrors = new List() - }; - - foreach (var propertyError in errorModel) - { - if (propertyError.key == "") - { - foreach (var error in propertyError.errors) - { - formResult.Message += error; - - if (propertyError.errors.Length > 1 && error != propertyError.errors.Last()) - formResult.Message += "
"; - } - - continue; - } - - var errorMessage = new StringBuilder(); - - foreach (var error in propertyError.errors) - { - errorMessage.Append(error); - - if (propertyError.errors.Length > 1 && error != propertyError.errors.Last()) - errorMessage.Append("
"); - } - - formResult.ValidationErrors.Add(new FormResultValidationError - { - PropertyName = propertyError.key, - Message = errorMessage.ToString() - }); - } - - context.Result = new JsonResult(formResult); - } - } - else - { - var services = httpContext.RequestServices; - - var metadataProvider = services.GetService(); - - var currentModel = context.ActionArguments.Values - .Where(v => !v.GetType().FullName.StartsWith("System.")) - .FirstOrDefault(); - - var viewResult = new ViewResult - { - ViewData = new ViewDataDictionary(metadataProvider, modelState) - }; - - if (!string.IsNullOrWhiteSpace(ViewName)) - { - viewResult.ViewName = ViewName; // "Index"; "../HomeTest/Index" - } - - viewResult.ViewData.Model = currentModel; - - context.Result = viewResult; - } - - base.OnActionExecuting(context); - } - - public override void OnActionExecuted(ActionExecutedContext context) - { - base.OnActionExecuted(context); - } - } + [AttributeUsage(AttributeTargets.Method)] + public class FormValidator : ActionFilterAttribute + { + public bool ValidateAntiforgeryToken { get; set; } = true; + public bool UseAjax { get; set; } = true; + public string ViewName { get; set; } + + + public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var httpContext = context.HttpContext; + + var antiForgery = httpContext.RequestServices.GetService(); + if (ValidateAntiforgeryToken) + { + await antiForgery.ValidateRequestAsync(httpContext); + } + + await base.OnActionExecutionAsync(context, next); + } + + public override void OnActionExecuting(ActionExecutingContext context) + { + var httpContext = context.HttpContext; + var modelState = context.ModelState; + + + if (UseAjax) + { + if (!httpContext.Request.IsAjaxRequest()) + { + context.Result = new ContentResult() + { + Content = "The request is not in the expected format. Check jQuery is loaded!", + StatusCode = StatusCodes.Status400BadRequest + }; + + return; + } + + if (!modelState.IsValid) + { + var errorModel = + from x in modelState.Keys + where modelState[x].Errors.Count > 0 + select new + { + key = x, + errors = modelState[x].Errors. + Select(y => WebUtility.HtmlEncode(y.ErrorMessage)). + ToArray() + }; + + var formResult = new FormResult(FormResultStatus.Error) + { + ValidationErrors = new List() + }; + + foreach (var propertyError in errorModel) + { + if (propertyError.key == "") + { + foreach (var error in propertyError.errors) + { + formResult.Message += error; + + if (propertyError.errors.Length > 1 && error != propertyError.errors.Last()) + formResult.Message += "
"; + } + + continue; + } + + var errorMessage = new StringBuilder(); + + foreach (var error in propertyError.errors) + { + errorMessage.Append(error); + + if (propertyError.errors.Length > 1 && error != propertyError.errors.Last()) + errorMessage.Append("
"); + } + + formResult.ValidationErrors.Add(new FormResultValidationError + { + PropertyName = propertyError.key, + Message = errorMessage.ToString() + }); + } + + context.Result = new JsonResult(formResult); + } + } + else + { + var services = httpContext.RequestServices; + + var metadataProvider = services.GetService(); + + var currentModel = context.ActionArguments.Values + .Where(v => !v.GetType().FullName.StartsWith("System.")) + .FirstOrDefault(); + + var viewResult = new ViewResult + { + ViewData = new ViewDataDictionary(metadataProvider, modelState) + }; + + if (!string.IsNullOrWhiteSpace(ViewName)) + { + viewResult.ViewName = ViewName; // "Index"; "../HomeTest/Index" + } + + viewResult.ViewData.Model = currentModel; + + context.Result = viewResult; + } + + base.OnActionExecuting(context); + } + + public override void OnActionExecuted(ActionExecutedContext context) + { + base.OnActionExecuted(context); + } + } } diff --git a/src/FormHelper/TagHelpers/FormTagHelper.cs b/src/FormHelper/TagHelpers/FormTagHelper.cs index fe293bb..85812db 100644 --- a/src/FormHelper/TagHelpers/FormTagHelper.cs +++ b/src/FormHelper/TagHelpers/FormTagHelper.cs @@ -37,7 +37,9 @@ public FormHelperTagHelper(IHtmlGenerator generator) : base(generator) [HtmlAttributeName("asp-toastrPosition")] public ToastrPosition? ToastrPosition { get; set; } - public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) + [HtmlAttributeName("asp-checkTheFormFieldsMessage")] + public string CheckTheFormFieldsMessage { get; set; } + public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var usedFormHelperTag = output.TagName == "formhelper"; @@ -80,9 +82,9 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu output.Attributes.Add("enableButtonAfterSuccess", EnableButtonAfterSuccess); output.Attributes.Add("resetFormAfterSuccess", ResetFormAfterSuccess); - output.Attributes.Add("checkTheFormFieldsMessage", configuration.CheckTheFormFieldsMessage); + output.Attributes.Add("checkTheFormFieldsMessage", CheckTheFormFieldsMessage ?? configuration.CheckTheFormFieldsMessage); - if (usedFormHelperTag) + if (usedFormHelperTag) { await base.ProcessAsync(context, output); }