Home > Blockchain >  Ajax.BeginForm() not calling the method and calls directly Javascript method in OnSuccess
Ajax.BeginForm() not calling the method and calls directly Javascript method in OnSuccess

Time:07-25

I am working with ASP MVC 5 and I have been using Ajax.BeginForm() in many of my views, but there has only been issues on one of the view. As I submit a form using Ajax.BeginForm, the method defined was not called, there isn't any errors triggered or catched, and it goes directly to the callback of OnSuccess without loading any actions in the method.

I have tried to search for a similar issue and found that it could be because of typo or the type of model but I have checked everything, there isn't such mistakes at all. Hence I would like to know if any of us here encountered similar problems.

Just to test things out, I tried simple Post'ing and it doesn't work as well.

Stats.cshtml

@model Example.ViewModels.StatsViewModel
@using (Ajax.BeginForm("Test", "Statistic", null, new AjaxOptions { HttpMethod = "POST", OnSuccess="alert('test')" }))
{
    @Html.AntiForgeryToken()
    <button  type="submit"><i ></i>Filter</button>
}

StatisticController.cs

[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult Test(StatsViewModel test)
{       
    StatsViewModel vm = new StatsViewModel
    {
       [...]
    };
    return PartialView("Test", vm);
}

Results : the alert is triggered first

P.S.:

  • I have checked if the method is called by placing debug points in the IDE and only this method here isn't pausing at any debug point
  • I have checked if i have the jquery.unobtrusive-ajax.js included and evidently, it is present and hence I have lost any possible clue of why is it skipping the method call and falling directly into OnSuccess callback.

Thank you in advance for any possible solutions.

CodePudding user response:

As I see, the problem occur on posting the form to an action method. Resolution.

  1. You must add <add key="UnobtrusiveJavaScriptEnabled" value="true" /> to your web config <appSettings>
  2. In the view page add the following JS file references
  • <script src="~/Scripts/jquery-{version}.js"></script>
  • <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>

CodePudding user response:

I found out that it was because of one of the routes in the same controller that accepts a string as its route parameter.

It is not supposed to be redirected to that but since the other routes aren't explicitly declared, hence it was redirected to that route by default when Ajax does the POST.

Thank you for the help.

  • Related