如果您尝试在 .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 库正常工作。