Javascript event handler is not intercepting the f

2019-07-29 18:45发布

I am using asp.net mvc 4 razor and I have a main view that has some checkboxes and a submit button. Those checkboxes indicates the tasks to be performed. User selects the tasks to be performed through the checkboxes and then he launch the process by clicking on the submit button. I have a div block on which I want to put the progress of the action in the controller, the tasks they are currently being done.

Once the submit button is clicked, I want first script to be launched (the main one) and then on complete next tasks will be done.

The problem is that first main script which then calls the others in sequence is not being called.

I am using ASP.NET MVC 4

Below the code.

View:

@using (Html.BeginForm(
     "PerformTasks", "Tests", FormMethod.Post,
     htmlAttributes: new { id = "frm" }))
{ 
   (...)
       @Html.CheckBoxFor(m => m.task01)<span>Task 1</span><br />
       @Html.CheckBoxFor(m => m.task02)<span>Task 2</span><br />
   (...)
       <input type="submit" value="Do Tasks" />
       <div id="divStatus">
       </div>
}

<script>

// First ajax script
$("#frm").submit(function (event) {
    $("#frm").validate();
    if ($("#frm").valid()) {
       $.ajax({
                url: "/Tests/PerformTasks/",
                type: 'POST',
                data: $("#frm").serialize(),
                success: function() {            
                          perFormTask1();
                },
                beforeSend: function() { 
                     $("#divStatus").append('<br/>Begginig tasks...<br/>'); 
                }           
       });
       event.preventDefault();
    }
});

// second ajax script
function performTask1() {
  $.ajax({
    url: "/Tests/Task1/",
    type: 'POST',
    data: $("#frm").serialize(),
    success: function() { 
        $("#divStatus").append('Task1 completed.<br/>');           
        perFormTask2();
    },
    beforeSend: function() { 
        $("#divStatus").append('<br/>Begginig task 1...<br/>'); 
    }            
  });
};

function performTask2() {
  $.ajax({
    url: "/Tests/Task2/",
    type: 'POST',
    data: $("#frm").serialize(),
    success: function() { 
        $("#divStatus").append('Task2 completed.<br/>');
    },
    beforeSend: function() { 
        $("#divStatus").append('<br/>Begginig task 2...<br/>'); 
    }            
  });
};

</script>

Controller (TestsController.cs under \Controllers):

public class TestsController : Controller
{
  [HttpPost]
  public ActionResult PerformTasks(ViewModel model)
  {
      // Nothing to do here, tasks are done individually in the methods below.
      // To stay in the same page after submit button is clicked
      return Redirect(this.Request.UrlReferrer.AbsolutePath);
  }

  [HttpPost]
  public ActionResult Task1(ViewModel model)
  {
     // Task 1 should be done if checkbox in the main view is checked, otherwise not.
     bool doTask1 = model.task01;
     if (doTask1 )
     {
       // Do some stuff
     }         

     // To stay in the same page after submit button is clicked
     return Redirect(this.Request.UrlReferrer.AbsolutePath);
  }

  [HttpPost]
  public ActionResult Task2(ViewModel model)
  {
    // Task 2 should be done if checkbox in the main view is checked, otherwise not.
    bool doTask2 = model.task02;
    if (doTask2)
    {
       // Do some stuff
    }

    // To stay in the same page after submit button is clicked
    return Redirect(this.Request.UrlReferrer.AbsolutePath);
  }
}

The view model:

public class ViewModel
{
    public bool task01{ get; set; }
    public bool task02{ get; set; }
}

I have below issues :

  1. I should put instead of because if not, I get the error message javascript '$' is not defined
  2. this script $("#frm").submit(function (event) { ... // body ... } is not being executed so neither the rest of actions on this completes. And so event complete of the first script is not being reached.

Note:I have checked that the action PerformTasks in the controller is being reached. The others actions Task1, Task2 on the controller are not being reached. In the scripts instead of success I have tried complete but without success. Also I have tried to replace ActionResult in actions in the controlled by JsonResult and return return Redirect(...) to return Json("") but also without success.

It seems like Javascript event handler is not intercepting the form submission.

Any ideas?

Code generated:

<form action="/Tests/PerformTasks" id="frm" method="post"><fieldset style="margin-top:20px;margin-left:0px;float:left;"> 
   .... 
   <input type="submit" value="Execute" /> 
   ...
   <div id="divStatus"></div>
   ...
</form>

and then below the scripts:

<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript">
    alert("Within Script");
    $("#frm").submit(function (event) { .. });
    ...
</script> 

The scripts are the same as posted here.

1条回答
神经病院院长
2楼-- · 2019-07-29 18:55

You aren't surrounding your form submit handler in a document.ready, it will be activated before the form is in the DOM.

<script type="text/javascript">
    $(document).ready(function(){
        $("#frm").submit(function (event) { 
            var form = $(evt.currentTarget);

            if(!form.validate().valid()) // you'll need to check this line
                return false;

             PerformTask();
             event.preventDefault();
             return false;
        });

    });
</script> 

I think your first form is doing a full postback. if you monitor the network tab in chrome while you do the form submit, if you see it was requested by jquery or something like that, you know you are doing a partial postback.

hth

查看更多
登录 后发表回答