Ajax.beginform does a full postback

1.2k views Asked by At

I am using Ajax,beginform to get partial postback, have install the Microsoft.jQuery.Unobtrusive.Ajax package, set up the bundle and added the keys in config files. With all this done when i click my submit button i get full postback. Have gone though tones of post and tried all suggested solutions, still seems to not work. is there anything i am still missing.

@using (Ajax.BeginForm("MyAction", "MyController", new AjaxOptions()
 {
       HttpMethod = "GET",
       UpdateTargetId = "divList",
       InsertionMode = InsertionMode.Replace
  }))
  {
       <button type="submit"><span><span class="sr-only">Show more List</span></span></button>
  }
 <div id="divList">
     @Html.Partial("_MyList.cshtml", Model.List)
 </div>

In my controller

    public ActionResult MyAction()
    {
        .....
        return PartialView("_MyList", list);
    }

Added in the bundle

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                          "~/Scripts/jquery.unobtrusive*",
                          "~/Scripts/jquery.validate*"));

In web.config

  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

Have even tried setting the section script in my view

@section Scripts {
  @Scripts.Render("~/bundles/jquery")
  @Scripts.Render("~/bundles/bootstrap")
  @Scripts.Render("~/bundles/jqueryval")
}
1

There are 1 answers

0
Sukesh Chand On

Another best way to handle the scenario is, instead of Ajax.BeginForm use Html.BeginForm

Use JQuery form submit, this will help you to stay away from jquery.unobtrusive

In .cshtml

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { id = "form_" + @Model.Id }))
    {
        <div>
            @Html.HiddenFor(m => m.AntiForgeryToken, new { @class = "form-control" })
            @Html.HiddenFor(m => m.Id, new { @class = "form-control" })

            <button onclick='onClickFormButton("[email protected]")' type="button">Submit</button>
        </div>
    }

Javascript

window.onClickFormButton = function (formId) {
    //validate the form clientside
    var validateResult = OnValidateForm(formId);
    if (!validateResult) return false;

    var form = $('#' + formId);
    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function (result) {
            // process the result
            processSuccessResult(result)
        },
        fail: function (result) {
            // process the result
            processFailResult(result)
        }
    });
    return false;
}

Controller/Action

[HttpPost]
public JsonResult ActionName(FormCollection model)
{
    // Get  id
    var idKey = model.AllKeys.FirstOrDefault(x => x.Contains("Id"));
    var id = model[idKey];
    
    return new ProcessedResult(id);
}