Asp.net MVC core 中替代 Ajax.BeginForm 的方法是什么?

3

我认为在asp.net MVC core中我们不再有使用Ajax.BeginForms的选项了...那么Ajax.BeginForm的替代方法是什么?

2个回答

2
您可以使用内联的data-ajax-*属性:
<form method="get"
      data-ajax-="true"
      data-ajax-method="get"
      data-ajax-url="/test">
      ...
</form>
  • data-ajax:设置为“false”将禁用此功能
  • data-ajax-url:定义发出请求的URL地址
  • data-ajax-method:定义使用的HTTP方法(例如GET或POST)
  • data-ajax-mode:定义期望的响应数据类型
  • data-ajax-update:指定要更新的DOM元素
  • data-ajax-loading:指定要显示的元素,直到请求完成
  • data-ajax-loading-duration:指定显示加载元素的时间
  • data-ajax-confirm:定义在发送请求之前要提示用户的消息
  • data-ajax-begin:定义在请求之前要执行的JavaScript函数
  • data-ajax-complete:定义当请求完成时要执行的JavaScript函数
  • data-ajax-failure:定义在请求失败时要执行的JavaScript函数
  • data-ajax-success:定义在请求成功时要执行的JavaScript函数

有关示例,请参见使用内联属性的Ajax请求

或者您可以从<scripts>标签中调用$.ajax

$.ajax({
  url: "test.html",
  context: document.body
}).done(function() {
  $( this ).addClass( "done" );
});

更多细节请参见jQuery.ajax()


2
你可以使用 https://github.com/mjebrahimi/AspNetCore.Unobtrusive.Ajax 来实现无障碍Ajax。
  1. Install nuget package called: AspNetCore.Unobtrusive.Ajax

  2. In startup in ConfigureServices add the following line services.AddUnobtrusiveAjax(useCdn: true, injectScriptIfNeeded: false);

  3. In razor page place @Html.RenderUnobtrusiveAjaxScript() at the end of body and after jquery Example of using instead of Ajax.BeginForm call:

    using (Html.AjaxBeginForm("SendComment",
    new AjaxOptions
    {
        HttpMethod = "Post",
        InsertionMode = InsertionMode.InsertAfter,
        UpdateTargetId = $"comments{Model.ExerciseId}",
        OnBegin = "ExerciseScripts.toggleLoading($(this), $(this));",
        OnSuccess = $"ExerciseScripts.toggleLoading($(this), $(this)); $('#textarea{Model.ExerciseId}').val('');",
        OnFailure = "Notice.showError();"
    }))
    {
        @Html.AntiForgeryToken()
        @Html.Hidden("exerciseId", Model.ExerciseId)
        @Html.TextArea("Comment", "",
            new {
                id = $"textarea{Model.ExerciseId}",
                @class = "form-control",
                placeholder = "Write you comment",
                required ="required"
            })
        <br />
        <button type="submit" class="btn btn-primary">
            <i class="fa fa-paper-plane-o fa-lg"></i>
            <span>Send</span>
        </button>
    }
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接