Code Monkey home page Code Monkey logo

formhelper's Introduction

Form Helper

#1 Form Library for ASP.NET Core MVC

If you like this library and want to support it, please give a star. ⭐

Form & Validation Helper for ASP.NET Core MVC

Form Helper helps you to create ajax forms and validations without writing any javascript code. It transforms server-side validations to client-side. You can also use the form validator without ajax.

Compatible with Fluent Validation

(You can add client-side validation support to Fluent Validation.)

NuGet Nuget

FormHelper

Installation

FormHelper can be installed using the Nuget Package Manager or the dotnet CLI.

Package Manager:

Install-Package FormHelper

dotnet CLI:

dotnet add package FormHelper

This library works with jQuery

CDN:

<!-- form helper - You don't need to add these files to your project, just add it. it's embeded! -->
<!-- if you dont't want to use these embeded files, you can download the files from dist folder -->
<!-- You can use formhelper.js/css instead of formhelper.min.js/css to debug. -->
<!-- The bundle file includes jQuery validation and jQuery validation unobtrusive -->

<link rel="stylesheet" href="/formhelper/formhelper.min.css" />
<script src="/formhelper/formhelper.bundle.min.js"></script>

Usage

Startup.cs

ConfigureServices:

services.AddControllersWithViews().AddFormHelper();

With configuration: (optional)

services.AddControllersWithViews().AddFormHelper(options => {
    options.CheckTheFormFieldsMessage = "Your custom message...";
    options.RedirectDelay = 6000;
    options.EmbeddedFiles = true;
    options.ToastrDefaultPosition = ToastrPosition.TopFullWidth;
});

Configure:

<!-- If you want to use embeded form helper files, 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="javascriptFunctionName", asp-beforeSubmit="javascriptFunctionName", asp-dataType="FormData/Json", asp-enableButtonAfterSuccess="false", asp-resetFormAfterSuccess="true" asp-toastrPosition="ToastrPosition.BottomRight"

Controller:

[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 a result from Controller:

Error Message:

return FormResult.CreateErrorResult("An error occured.");

Success Message:

return FormResult.CreateSuccessResult("Product saved.");

Success Message with Redirect:

return FormResult.CreateSuccessResult("Product saved. Please wait...", Url.Action("Home", "Index"));

Success Message with Redirect and Delay Time:

return FormResult.CreateSuccessResult("Product saved. Please wait...", Url.Action("Home", "Index"), 10000); // 10 seconds

Fill the form fields from a json object:

$("#formId").fillFormFields(yourJsonObject);

Reset form and clear error messages:

$("#formId").fhReset();

Toastr:

Success:

fhToastr.success("Text here");

Warning:

fhToastr.warning("Text here");

Information:

fhToastr.information("Text here");

Error:

fhToastr.error("Text here");

formhelper's People

Contributors

basarburak avatar dependabot[bot] avatar dogukantansuk avatar fatihcandan52 avatar sinanbozkus avatar vgunduzalp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formhelper's Issues

Support Pascal Case Json Serializer?

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?

FormResult CreateResult to execute javascript function

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

Razorpages wont redirect after POST

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:

image

My page never navigates:

image

Looks like Form Helper takes over the post, and instead makes it an AJAX call? Shouldn't it respect a 302?

Toastr position TopCenter not working as expected

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.

Model value not getting in JavaScript after form post method called.

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.

Use Validation Summary

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

The request is not in the expected format. Check jQuery is loaded!

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.

The request is not in the expected format. Check jQuery is loaded!

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.

beforeSubmit throws error if handler uses "object.method()" format

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

Before submit Function

We need a pre-request callback function before submit. Does FormHelper have this function?

Add an option to localize Toastr messages

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.

Asp.net core razor desteği

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;
    }
}

The request is not in the expected format. Check jQuery is loaded!

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.

Cannot find compilation library location for package 'Microsoft.NETCore.App'

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)

Use pascalcase in callback

Response in callback function comes "camelCase" when "UsePascalCase" property is true. Telerik uses Pascalcase style.

validate modal

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!"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.