sinanbozkus / formhelper Goto Github PK
View Code? Open in Web Editor NEWASP.NET Core - Transform server-side validations to client-side without writing any javascript code. (Compatible with Fluent Validation)
License: MIT License
ASP.NET Core - Transform server-side validations to client-side without writing any javascript code. (Compatible with Fluent Validation)
License: MIT License
Response in callback function comes "camelCase" when "UsePascalCase" property is true. Telerik uses Pascalcase style.
After the call form post method, I return the view with the model object in view but I am not able to get the model result in my view javascript code.
Code :
console.log("respone result", '@Model.Response');
I expect @Model.Response will be 1. it always returns 0 after the FormCallback method is called.
Please let me know what I am missing for this.
We need a pre-request callback function before submit. Does FormHelper have this function?
Hocam öncelikle elinize sağlık.. gerçekten de çok başarılı..
yukardaki hatayı aldım sonra sizin komutları yaptım hata giderilmedi. sonra denerken hatanın sweetalert2 den kaynaklı olduğunu gördüm. kullanmayınca formhelper düzeldi.
sweetalert2 yerine sweetalert kullandım bu kez de submit button tıklanmasıyla hem tostr hem de sweetalert aynı anda çalıştı :D
çözüm olarak bir input u button type olarak önce swal çağırdım submit durumunda form buttonu çağırdım tabi gizlemek zorunda kaldım vs.. kendimce yollar anlayacağınız. daha kolay bir çözümünüz varsa destek olabilir misiniz? ya da bu yöntem ok mi? ilerde sweetalert2 için update olur mu?
teşekkür ederim şimdiden.
If options.ToastrDefaultPosition = ToastrPosition.TopCenter
, the actual toastr position is BottomFullWidth. This is caused by a typo at line 53 & 54 in Extensions/FormHelperExtensions.cs
:
case ToastrPosition.TopCenter:
return "formhelper-toast-bottom-full-width";
Please kindly check and fix.
I got an exception in the view when I use the RenderFormScript.
The error message is:
System.InvalidOperationException: Cannot find compilation library location for package 'Microsoft.NETCore.App'
Exception StackTrace:
System.InvalidOperationException: Cannot find compilation library location for package 'Microsoft.NETCore.App'
at Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths(ICompilationAssemblyResolver resolver, List`1 assemblies)
at Microsoft.Extensions.DependencyModel.CompilationLibrary.ResolveReferencePaths()
at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.<>c.<GetReferencePaths>b__8_0(CompilationLibrary library)
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
at Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable`1 parts, MetadataReferenceFeature feature)
at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature)
at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.GetCompilationReferences()
at System.Threading.LazyInitializer.EnsureInitializedCore[T](T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory)
at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.get_CompilationReferences()
at Microsoft.AspNetCore.Mvc.Razor.Internal.LazyMetadataReferenceFeature.get_References()
at Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature.GetDescriptors()
at Microsoft.AspNetCore.Razor.Language.DefaultRazorTagHelperBinderPhase.ExecuteCore(RazorCodeDocument codeDocument)
at Microsoft.AspNetCore.Razor.Language.RazorEnginePhaseBase.Execute(RazorCodeDocument codeDocument)
at Microsoft.AspNetCore.Razor.Language.DefaultRazorEngine.Process(RazorCodeDocument document)
at Microsoft.AspNetCore.Razor.Language.DefaultRazorProjectEngine.ProcessCore(RazorCodeDocument codeDocument)
at Microsoft.AspNetCore.Razor.Language.RazorProjectEngine.Process(RazorProjectItem projectItem)
at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(String relativePath)
at Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.OnCacheMiss(String normalizedPath)
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(String relativePath)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet`1 expirationTokens, String relativePath, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, String pageName, Boolean isMainPage)
at Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, String viewName, Boolean isMainPage)
at FormHelper.FormHelperViewRenderService.RenderToStringAsync(String viewName, Object model)
at FormHelper.FormHelperHtmlHelpers.RenderFormScript(IHtmlHelper html, FormConfig config)
at AspNetCore.Views_Anket_Detay.ExecuteAsync() in C:\DefaultAgent\_work\52\s\ProjectName\ProjectName\Views\Folder\View.cshtml:line 1215
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, Boolean invokeViewStarts)
at Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, String contentType, Nullable`1 statusCode)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync(IActionResult result)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResultFilterAsync[TFilter,TFilterAsync]()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultFilters()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.Invoke(HttpContext context)
Sinan merhaba,
Kütüphaneni çok beğendim, aşağıdaki yorumlarımın ,razor tarafı içinde geliştirme yapmak istersen yararlı olacağını düşünüyorum.
Asp.net core razor da action filters mevcut değil onun yerine pagefilters var.Ayrıca antiforgery token kontrolü otomatik olarak yapılıyor.Bunun için hiç bir şey yapmaya gerek yok.
Benim gibi Razor kullananlar için aşağıdaki filteriyi yazdım.
Bunların seninde bildiğin gibi normalde scriptler dom bloklamamak adına body tag inin altına yazılır.Böyle olunca FormHelperTagHelper in eklediği script satırı daha jquery yüklenmediği $ undefined hatası veriyor.Orayı da javascript window load ile fonksiyonu ile değiştirdim.<script>window.addEventListener('load',function () {{$('#{formId}').UseFormHelper()
public class FormValidatorRazor : IAsyncPageFilter
{
public bool UseAjax { get; set; } = true;
/// <summary>
/// Called before the handler method executes, after model binding is complete.
/// </summary>
/// <param name="context"></param>
/// <param name="next"></param>
/// <returns></returns>
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
if (context.HttpContext.Request.Method.Equals("POST") || context.HttpContext.Request.Method.Equals("PUT"))
{
var httpContext = context.HttpContext;
var modelState = context.ModelState;
if (UseAjax)
{
if (!httpContext.Request.IsAjaxRequest())
{
if (context.HandlerInstance is PageModel result) //using pattern matching
{
result.Response.StatusCode = 400;
context.Result = result.Page();
}
await Task.CompletedTask;
}
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<FormResultValidationError>()
};
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 += "<br>";
}
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("<br>");
}
formResult.ValidationErrors.Add(new FormResultValidationError
{
PropertyName = propertyError.key,
Message = errorMessage.ToString()
});
}
context.Result = new JsonResult(formResult);
return;
}
}
else
{
var services = httpContext.RequestServices;
var metadataProvider = services.GetService<IModelMetadataProvider>();
var currentModel = context.HandlerInstance;
var viewResult = new ViewResult
{
ViewData = new ViewDataDictionary(metadataProvider, modelState)
};
viewResult.ViewData.Model = currentModel;
context.Result = viewResult;
}
}
await next.Invoke();
}
public async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
{
await Task.CompletedTask;
}
}
hi, im having an issue using. the validation doesnt happen. the post hits to my backend.
i have a modal which posts data using ajax. i tried to implement seeing the sample from github. but the modal validator in the sample also does not work. please help me achieve this.
i get this error when running the sample remote modal "The request is not in the expected format. Check jQuery is loaded!"
Version:FormHelper 4.0.1
I have been able to receive callbacks to a function defined within a named closure (?) but the same format does not seem to work for asp-beforeSubmit. I noticed in the source that the callback happens through a callFunction() method which splits the callback name and retrieves it one part at a time. The beforeSubmit code though just calls windowoptions.beforeSubmit which fails with "window[options.beforeSubmit] is not a function".
Thanks!
James
Hello all,
Can I use a validation summary instead of a "span with asp-validation-for" to show the error messages?
How do I do it?
I tried to put the tag <div asp-validation-summary="All"></div>
but seems like it doesn't work. The message does not show up if I don't have the spans for each field.
Thanks,
Kristian Fernando
merhaba,
formu kontrol ederken şu hata ile karşılaşıyorum.. yeni bir sekmede "The request is not in the expected format. Check jQuery is loaded!" mesajı karşılıyor..
adımların hepsini gerçekleştirdim.
FormValidator'u kaldırdığımda sorunsuz kullanabiliyorum.
It would be great if the CreateMethod can have an additional parameter to execute a function from my javascript library.
We don't want to redirect but instead, we want to create a custom logic after the post is successful. We can make this possible if we can specify a custom function name (with optional data) so the app can make a custom action.
For example:
FormResult.CreateResult(FormResultStatus.Success, "",null,null,"OpenModalFunction", "#modal-id")
Method will looks like:
public static JsonResult CreateResult(FormResultStatus status, string message, string redirectUri = null, int? redirectDelay = null, string executeFunction = null, string[] executeFunctionParameters = null);
We currently use a function that can be implemented with this solution so you can call any function by name in the Javascript:
Stackoverflow: https://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string
My razorpages code is as follows:
[BindProperty]
public CreateTeamViewModel CreateTeamRequest { get; set; } = default!;
public async Task<IActionResult> OnPostAsync(CancellationToken cancellationToken)
{
var result = await this.validator.ValidateAsync(this.CreateTeamRequest!, cancellationToken);
if (!result.IsValid)
{
result.AddToModelState(this.ModelState);
return this.Page();
}
var newTeam = new Team
{
// .....
};
this.context.Teams.Add(newTeam);
await this.context.SaveChangesAsync(cancellationToken);
return this.RedirectToPage("/Teams/Invite", new { teamId = newTeam.Id });
}
Chrome sees the 302:
My page never navigates:
Looks like Form Helper takes over the post, and instead makes it an AJAX call? Shouldn't it respect a 302?
My colleague use NewtonsoftJson.DefaultContractResolver as Json Serializer.
so the result becomes
{"Status":1,"Message":"Product saved.","RedirectUri":null,"RedirectDelay":null,"Object":null,"ValidationErrors":null,"IsSucceed":true}
my current workaround:
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; return Json(new FormResult(FormResultStatus.Success) { Message = "Product saved." }, settings);
Any other suggestions for this?
While you can currently specify a string to use for Toastr messages during the configuration, there's no obvious / easy way to setup a localized string.
I'd like to be able to either localize that string or disable the Toasts all together if that's not possible.
I worked around that issue by adding a CSS rule to hide the formhelper-toast-container
element.
Merhabalar Sinan,
Öncelikle eline sağlık çok güzel bir servis geliştirmişsin.
Ben başarılı bir şekilde kurduğumu düşünüyorum ancak "The request is not in the expected format. Check jQuery is loaded!" hatayı almaktayım, tekrar tekrar kurdum ama aynı hata sizce neden olabilir.
Teşekkürler.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.