John John
John John

Reputation: 1

What is the alternative to Ajax.BeginForms in Asp.net MVC core

I think in asp.net MVC core we no more have the option to use Ajax.BeginForms .. so what is the alternative for Ajax.BeginForm ?

Upvotes: 3

Views: 2186

Answers (2)

alanextar
alanextar

Reputation: 1314

You can use https://github.com/mjebrahimi/AspNetCore.Unobtrusive.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>
    }
    

Upvotes: 2

LazZiya
LazZiya

Reputation: 5719

You can use inline data-ajax-* attributes :

<form method="get"
      data-ajax-="true"
      data-ajax-method="get"
      data-ajax-url="/test">
      ...
</form>
  • data-ajax
  • data-ajax-url
  • data-ajax-method
  • data-ajax-mode
  • data-ajax-update
  • data-ajax-loading
  • data-ajax-loading-duration
  • data-ajax-confirm
  • data-ajax-begin
  • data-ajax-complete
  • data-ajax-failure
  • data-ajax-success

See Ajax Request Using Inline Attributes for some samples

Or you can call $.ajax from inside <scripts> tag:

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

See jQuery.ajax() for more details.

Upvotes: 2

Related Questions