【问题标题】:How to create AJAX Form in Asp.Net Core如何在 Asp.Net Core 中创建 AJAX 表单
【发布时间】:2019-04-13 06:07:33
【问题描述】:
<form data-ajax="true" data-ajax-mode="replace" data-ajax-update="#results" asp-action="CreateCarClient" asp-controller="Account" method="post" enctype="multipart/form-data">

此表格无效

【问题讨论】:

  • 互联网上有很多例子。尝试其中一个,如果您有具体问题,请发布。请描述您希望您的代码做什么、它做了什么以及您遇到问题的地方。

标签: ajax asp.net-core asp.net-ajax


【解决方案1】:

如果您尝试在 .NET 5 中执行此操作,请像往常一样将 JQuery.Unobtrusive.Ajax 库添加到您的项目中,然后编写您自己的小标签助手!

这个非常基础,但您可以根据需要对其进行扩展。

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('#')}");
        }
    }
}

记得在你的_ViewImports.cshtml注册这个标签助手

@addTagHelper  MyProject.Helpers.TagHelpers.*, MyProject

用法示例:

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

请注意,“ReplaceId”DOM 元素必须以 # 开头,以便不显眼的 ajax 库正常工作。

【讨论】:

    【解决方案2】:

    您可以使用FormHelper 在 ASP.NET Core 上创建 ajax 表单。此外,FormHelper 还可以帮助您将服务器端验证转换为客户端。

    它非常易于使用。您只需将 asp-formhelper="true" 添加到您的表单标签。

    <form asp-formhelper="true" asp-controller="Home" asp-action="Save">
       // <input...
       // ...
    </form>
    

    您可以在FormHelper GitHub Page 上查看它的文档。你可以从Nuget下载那个包。

    【讨论】:

      【解决方案3】:

      您在 ASP.NET Core 中使用 jQuery Unobtrusive AJAX。您需要使用 npm install jquery.unobtrusive-ajax 将 jquery.unobtrusive-ajax 包安装到您的项目中,并在您的视图中添加对它的引用。

      查看剃须刀页面教程here

      This link 展示了我如何逐步使用代码的示例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-05
        • 2020-09-03
        • 2021-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多