3

I'm typing this question away from my computer so I don't have the exact code, but the question might be straightforward enough without it.

When I have a submit button directly within an Ajax form and I click the button directly to submit, everything works fine, and as expected. The Ajax.Form POSTs back to the controller which returns a partial view that is rendered inside the current View that I have.

But what I need is for a button to be clicked in the Ajax.Form, and for a JavaScript function to run. The JavaScript function will do some vaildation which decides whether to submit the Ajax.Form or not.

I have tried putting 2 buttons in the Ajax.Form, a hidden submit button and a regular button. I used the onclick event of the regular button to call my JavaScript function which then called the click method of the hidden submit button. (I have also tried just submitting the Ajax.Form directly with document.forms[formname].submit() )

This sort of works.. But not correctly for some reason. The Ajax.Form POSTs back to the controller but when a partial view is returned from the controller, the partial view is the only thing rendered, and it is rendered as basic html with no css/bootstrap.

What is the difference between actually clicking the submit button and doing so programmatically?

How can Achieve what I am trying to do?

Edit

 @using (Ajax.BeginForm("GetInstructorInfo", "Incident", FormMethod.Post, new AjaxOptions { OnBegin = "lookupInstructor();", UpdateTargetId = "InstructorInfo" }, new { @class = "form-inline", role = "form", @id = "instructorInfoForm", @name = "instructorInfoForm" }))
{

//code in here

}

Edit 2 / 3:

<script>
    function lookupInstructor()
    {
        if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0)   //Don't allow user to enter multiple instances of the same Instructor
        {
            document.getElementById("InstructorUsername").value = ''; //clear textbox value
            return false;
        }
        var userInputInstructor =  document.getElementById("InstructorUsername").value;
        $.ajax({
            url: '@Url.Content("~/Incident/LookUpUsername")',
            data: { userInput: userInputInstructor },
            success: function (result) {
                if (result.indexOf("not found") != -1){ //if not found

                    $("#InstructorNotFoundDisplay").show();
                    document.getElementById("InstructorUsername").value = ''; //clear textbox value

                    $('#InstructorInfo').empty();
                    return false;
                }
                else {
                    $("#InstructorNotFoundDisplay").hide();
                    return true;
                }
            }
        });
  }
</script>
11
  • If your using Ajax.BeginForm(), then you can use the OnBegin ajax option to run a script before submitting (and cancel the submit is necessary) Commented Dec 2, 2015 at 2:23
  • @Stephen Muecke I did look at trying to use the OnBegin(), but it didn't work right when I implemented it. I didn't know you could cancel the submit, how would you do that? Commented Dec 2, 2015 at 2:39
  • You just return false; in the function. e.g. function Validate() { if (isValid) { return true; } else { return false; } } and then in the ajax options OnBegin = "return Validate();" (but why people still use the obsolete Ajax methods instead of $.ajax() I'll never understand) Commented Dec 2, 2015 at 2:48
  • @StephenMuecke worked perfect! If you want to add this as an answer I will mark it as the answer. thank you very much. The reason I'm using whatever, ajax methods I have, is because i'm extremely new to web development, and I haven't had time to properly learn much at all. I'm just going off of previously written code I can reference for the time being. I can't wait to really sit down and learn this stuff. Commented Dec 2, 2015 at 3:02
  • @StephenMuecke Actually, It seems that the Ajax.BeginForm() still Posts back to the controller even if I specify { return false; } in the javascript function. I will add the header of the Ajax.BeginForm() to my OP. any reason the return false; isnt working? Commented Dec 2, 2015 at 3:41

1 Answer 1

3

You can use the OnBegin() ajax option to call a function that runs before the form is submitted (and return false if you want to cancel the submit). For example

function Validate() { 
    var isValid = // some logic
    if (isValid) { 
        return true; 
    } else { 
        return false;
    }
}

and then in the Ajax.BeginForm() options

OnBegin = "return Validate();"

Edit

Based on the edits to the question and the comments, you wanting to call an ajax function in the OnBegin() option which wont work because ajax is asynchronous. Instead, use jQuery.ajax() to submit you form rather than the Ajax.BeginForm() method (and save yourself the extra overhead of including jquery.unobtrusive-ajax.js).

Change Ajax.BeginForm() to Html.BeginForm() and inside the form tags replace the submit button with <button type="button" id="save">Save</button>and handle its .click() event

var form = $('#instructorInfoForm');
var url = '@Url.Action("GetInstructorInfo", "Incident")';
var target = $('#InstructorInfo');

$('#save').click(function() {
  if ($('input[name="Instructors['+userInputInstructor+'].Username'+'"]').length > 0) {
    ....
    return; // exit the function
  }
  $.ajax({
    ....
    success: function (result) {
      if (result.indexOf("not found") != -1) {
        ....
      }
      else {
        $("#InstructorNotFoundDisplay").hide();
        // submit the form and update the DOM
        $.post(url, form.serialize(), function(data) {
          target.html(data);
        });
      }
    }
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.