4

I need to check whether the data is already exists in the database before submitting the form using ajax. The most common scenario is the checking the availability of the username and email.

It's not working but I tested the ajax function without using the from control and it works fine. The project is created in MVC 3 VB.

Javascript:

$('#addSalesPeople').click(function () {
   $.post("ajax_functions/checkDuplicate.cshtml",
   {
      extension: document.getElementById('Extension').value,
      initials: document.getElementById('Initials').value
   },
      function (data, status) {
      alert("Data: " + data + "\nStatus: " + status);
   });
});

HTML:

@Using Html.BeginForm("Create", "SalesPeople", FormMethod.Post)
@Html.ValidationSummary(True)
@<fieldset>  
    ............................
    ..............................  

    @Html.TextBoxFor(Function(model) model.Extension, New With {.onkeyup = "javascript: charCounter(this,4);", .onblur = "javascript: zeroPad(this, 4)"})

    @Html.TextBoxFor(Function(model) model.Initials)

    <input id="addSalesPeople" class="btn span2" type="submit" value="Add" />

</fieldset>

-Thanks

Suchan Dongol
  • 95
  • 1
  • 11
  • `extension: "document.getElementById('Extension').value"` should be `extension: document.getElementById('Extension').value`, same for `initials`. Also `Not able to get it working` is not very descriptive. – Musa Nov 05 '12 at 21:27
  • you can use remote validation for this purpose see this [StackOverFlow][1] [1]: http://stackoverflow.com/questions/4752877/remote-validation-in-asp-net-mvc-3-how-to-use-additionalfields-in-action-method – Nighil Nov 06 '12 at 04:46

2 Answers2

11

You need to observe the submit event of the form.

Instead of

$('#addSalesPeople').click(function () {

use

$('#theFormId').submit(function () {

see: http://api.jquery.com/submit/

You can also disable the form submit and send it later manually:

$( '#theFormId' ).submit( function ( event ) {

    event.preventDefault();

    /* your AJAX code */

    $( '#theFormId' ).submit();
} );
feeela
  • 29,399
  • 7
  • 59
  • 71
5

I am posting a real tested code.

HTML: Simple form post button in @using

(Html.BeginForm())
{

//use your text box or other control here 
<input type="submit" id="Create" value="Create" class="btn btn-primary" />

}

JavaScript:

<script>

    $(document).ready(function () {

        $("form").submit(function (e) {
            e.preventDefault(); //prevent default form submit

            if ($(this).valid()) {

                var UserId= $('#UserId').val();

                $.ajax({
                    url: '/Home/CheckUserExist/',        //ControllerName/ActionName/
                    data: {
                        UserId: UserId                      
                    },
                    success: function (data) {
                        showMsg(data);
                    },
                    cache: false
                });
            }
        });

    });

    function showMsg(hasCurrentJob) {
        if (hasCurrentJob != "OK") {

            alert(hasCurrentJob);
            return false;
        } else {

    //if check is ok than from post to controller 

            $("form").unbind('submit').submit();
        }
    }

</script>


MVC Controller:

 public async Task<JsonResult> CheckUserExist(int UserId)
    {
            //condition for user check 

        if (UserExist==true)
        {
            return Json("User Exist Please choose another user name or etc", JsonRequestBehavior.AllowGet);         
    }

        return Json("OK", JsonRequestBehavior.AllowGet);
    }

if you have any query mail me vishalroxx7@gmail.com.

Vishal Sen
  • 1,135
  • 1
  • 13
  • 23