How to create AJAX Form in Asp.Net Core

<form data-ajax="true" data-ajax-mode="replace" data-ajax-update="#results" asp-action="CreateCarClient" asp-controller="Account" method="post" enctype="multipart/form-data">

This form is not work


Solution 1:

You are using jQuery Unobtrusive AJAX in ASP.NET Core.You need to install the jquery.unobtrusive-ajax package into your project using npm install jquery.unobtrusive-ajax and add references to it in your view.

See tutorials of razor pages here.

This link displays my example of how to use the code step by step.

Solution 2:

If you attempting to do this in .NET 5 then add the JQuery.Unobtrusive.Ajax libraries to your project as you normally would, then write your own little tag helper!

This one is VERY basic but you can expand on it as you wish.

namespace MyProject.Helpers.TagHelpers
{
    [HtmlTargetElement("form", Attributes ="ajax")]
    public class AjaxForm : TagHelper
    {
        public string replaceId { get; set; }
        public string onAjaxBegin { get; set; }
        public string id { get; set; }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagMode = TagMode.StartTagAndEndTag;
            output.Attributes.SetAttribute("data-ajax", "true");
            output.Attributes.SetAttribute("data-ajax-method", "POST");
            output.Attributes.SetAttribute("data-ajax-mode", "replace");
            output.Attributes.SetAttribute("method", "post");
            output.Attributes.SetAttribute("id", id);

            if (!string.IsNullOrWhiteSpace(onAjaxBegin))
                output.Attributes.SetAttribute("data-ajax-begin", onAjaxBegin);

            if (string.IsNullOrWhiteSpace(replaceId))
                throw new Exception("ReplaceId is required!");

            output.Attributes.SetAttribute("data-ajax-update", $"#{replaceId.TrimStart('#')}");
        }
    }
}

Remember to register this tag helper in your _ViewImports.cshtml

@addTagHelper  MyProject.Helpers.TagHelpers.*, MyProject

Usage Example:

  <form id="GandalfForm" ajax replace-id="partialViewWrapper" on-ajax-begin="OnBeginDoSomethingInJavascript" asp-controller="SomeController" asp-action="SomeMethod">
                    <div id="partialViewWrapper">
                        @await Html.PartialAsync("~/Views/Shared/SampleContent.cshtml", Model)
                    </div>

Note that the "ReplaceId" DOM element must start with a # in order for the unobtrusive ajax library to work correctly.