1

I am developing an MVC4 mobile app that uses several forms which are loaded into a section on the layout via ajax. I've got jQuery mobile set with Ajax turned off so I can manage the Ajax myself. Most of the forms work fine, the load and submit via ajax as they should. However, so far there is one form that refuses to fire the form submit and submit the form via ajax like the rest. First, the form is loaded when a user clicks to add a contact and this works fine:

// Handle the add contact button click
$('#btnAddNewContact').on('click', function (e) {
    e.preventDefault();
    // Make sure a location was selected first.
    var locationID = $('#cboLocation').val();
    if (locationID.length === 0) {
        //$('#alertTitle').text('REQUIRED');
        $('#alertMsg').html("<p>A Contact must be associated with a Location.</p><p>Please select or add a Location first.</p>");
        $('#alertDialogDisplay').click();            
    } else {
        SaveOpportunityFormState();
        $.cookie('cmdLocationId', locationID, { path: '/' });
        $.mobile.loading('show');
        $.ajax({
            url: '/Contact/Add',
            type: 'GET',
            cache: false,
            success: function (response, status, XMLHttpRequest) {
                $('section.ui-content-Override').html(response);
                // Refresh the page to apply jQuery Mobile styles.
                $('section.ui-content-Override').trigger('create');
                // Force client side validation.
                $.validator.unobtrusive.parse($('section.ui-content-Override'));
            },
            complete: function () {
                $.cookie('cmdPreviousPage', '/Opportunity/Add', { path: '/' });                    
                AddContactLoad();
                ShowSearchHeader(false);
                $.mobile.loading('hide');
            },
            error: function (xhr, status, error) {
                // TODO - See if we need to handle errors here.
            }
        });
    }
    return false;
});

Notice that after successfully loading the form the AddContactLoad() function is fired. This works fine and here is that code:

function AddContactLoad() {
$('#contactVM_Phone').mask('(999) 999-9999? x99999');                
$('#frmAddContact').on('submit', function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.mobile.loading('show');
        $.ajax({
            url: '/Contact/Add',
            type: 'POST',
            cache: false,
            data: $(this).serialize(),
            success: function (response, status, XMLHttpRequest) {
                if (!response) {  // Success
                    ReturnToAddOpportunity();
                } else {  // Invalid Form
                    $('section.ui-content-Override').html(response);
                    // Force jQuery Mobile to apply styles.
                    $('section.ui-content-Override').trigger('create');
                    // Force client side validation.
                    $.validator.unobtrusive.parse($('section.ui-content-Override'));
                    AddContactLoad();
                    $.mobile.loading('hide');
                }
            },
            complete: function () {

            },
            error: function (xhr, status, error) {
                // TODO - See if we need to handle errors here.
            }
        });
    }
    return false;
});
$('#btnCancel').on('click', function (e) {
    e.preventDefault();
    // See where add contact was called from.
    var previousPage = $.cookie('cmdPreviousPage');
    if (previousPage.indexOf("Detail") >= 0) {
        ReturnToOpportunityDetails();
    } else {
        ReturnToAddOpportunity();
    }
    return false;
});

}

If I click the cancel button, that code is fired so I know this is working too. Here is my form code:

@using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { @id = "frmAddContact" }))
{
@Html.ValidationSummary(true)
@Html.AntiForgeryToken()    

-- Form Fields Here --

<div class="savecancel" >
    <input type="submit" value="Save" data-mini="true", data-theme="b", data-inline="true" /> 
    <a href="#" id="btnCancel" data-role="button" data-inline="true" data-theme="b" data-mini="true">Cancel</a> 
</div>   
}

As you can see the form is named frmAddContact and that is what the AddContactLoad() function is attaching the submit event to. To save my sole I cannot figure out why the form does not submit via the ajax post like every other form in the app. Am I missing some kind of initialization, I just don't know. If anyone can please help I'd really appreciate it!!

4

1 に答える 1

0

As it turns out, I had created a custom unobtrusive Ajax validator for a phone number then copied and pasted it to do the same with a zip code. Unfortunately in the process I forgot to rename a variable and thus an error was occurring in the validation script which caused the problem. In the mean time, if you're reading this, you might take a note of the code here and how to inject HTML into a page via Ajax and jQuery mobile. I've never found this in a book or on the web and it contains some very useful methodology and syntax. On the form submit the reason I'm checking for the empty response is I just return null from the controller to validate the form was valid and the save worked in which case I send them to a different HTML injection i.e. that page they originally came from. If null is not returned I inject that page with the HTML containing the original form and error markup so the user can make corrections then resubmit. I'm also calling a form load method that attaches handlers to the HTML once it's injected into the main page. Hope this helps somebody!

于 2012-12-20T23:12:33.997 に答える