Jquery Ajax only works when in debug mode

Question!

I'm trying to teach myself MVC and jquery, but seem to be having problems posting data back to my controller via ajax. My idea was to display a list of type MealViewModel in my EditMenu view, then use a bootstrap modal to display a partial view when the chef wanted to insert a new meal or edit a meal. I haven't made it to the edit part yet.

Here is my EditMenu view:

@model IEnumerable<Test.Models.MealViewModel>
@using Test.Utilities;

@{
    ViewBag.Title = "Edit Menu";
}
<div class="container">
    <br />
    @Html.ActionLink("Insert New Meal ", "InsertMeal", "Chef", null, new { @class = "modal-link btn btn-primary" })
    <br /><br />
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.MealDescription)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MealDate)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.MealType)
           </th>
            <th></th>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.MealDescription)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.MealDate)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.MealType)
                </td>
                <td>
                    @Html.ActionLink(linkText: "Edit",
                    actionName: "EditMeal",
                    controllerName: "Chef",
                    htmlAttributes: new { @class = "modal-link btn btn-primary" },
                    routeValues: new { mealId = item.MealId })
                </td>
            </tr>
        }
    </table>
</div>

<div id="modal-container" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body"></div>
        </div>
    </div>
</div>

@section scripts {
    <script type="text/javascript">
        $(function () {
            $('body').on('click', '.modal-link', function (e) {
                e.preventDefault();
                $(this).attr('data-target', '#modal-container');
                $(this).attr('data-toggle', 'modal');
            });

            $('body').on('click', '.modal-close-btn', function () {
                $('#modal-container').modal('hide');
            });

            $('#modal-container').on('hidden.bs.modal', function () {
                $(this).removeData('bs.modal');
            });

           $('#cancel-button').on('click', function () {
            return false;
        });
    });
</script>

}

Here is my _EditMeal partial view, which is rendered in the bootstrap modal.

@model Test.Models.MealViewModel

<div class="modal-header">
    <div class="alert alert-info">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h1 class="modal-title">Create New Meal</h1>
    </div>
    <div class="modal-body">
        <form id="insertForm">
            <div class="form-horizontal">

               <div class="form-group">
                   <label class="control-label col-md-2">Description: </label>
                    <div class="col-md-10">
                        <input type="text" id="meal-description" class="form-control" name="description" />
                   </div>
                </div>

               <div class="form-group">
                    <label class="control-label col-md-2">Date:</label>
                    <div class="col-md-10">
                        <input id="meal-date" class="form-control" type="date" name="date" />
                   </div>
               </div>

                <div class="form-group">
                    <label class="control-label col-md-2">Type:</label>
                    <div class="col-md-10">
                        <select id="meal-type" class="form-control" name="type">
                            <option value="Breakfast">Breakfast</option>
                            <option value="Dinner">Dinner</option>
                        </select>
                    </div>
                </div>

               <div class="form-group">
                   <div class="col-md-offset-2 col-md-10">
                       <input type="submit" value="submit" class="btn btn-default submitMeal" id="submit-button" />
                    </div>
                </div>

           </div>
        </form>
   </div>
</div>

<script type="text/javascript">
       $("#submit-button").on('click', function () {

        var meal = {
            "MealDescription": $("#meal-description").val(),
            "MealDate": $("#meal-date").val(),
            "MealType": $("#meal-type").val()
        };

        $.ajax({
            type: "POST",
            cache: false,
            url: '@Url.Action("InsertMeal", "Chef")',
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify(meal),
            dataType: "json"
        });
    });
</script>

And my controller:

    // Insert new meal
    [HttpPost]
    public ActionResult InsertMeal(MealViewModel newMeal)
    {
        repo.InsertMeal(newMeal);

        List<MealViewModel> allMeals = repo.GetAllMeals().ToList();

        return View("EditMeal", allMeals);
    } 

Everything seems to work, but only when inserting debugger; in the script tag in the _EditMenu view and stepping through my code. I've spent some time on Google trying to find a solution, but I have come up empty. I've tried adding cache: false to the ajax post, used @Url.Action() to properly render the url, but nothing seems to work. As soon as I exit debug mode, the ajax call never hits my controller and fails every time. Why does my ajax post only work when debugging?

Note: Bootstrap, Jquery, jquery.validate, and jquery.unobtrusive-ajax are all bundled and render on my shared _layout page.



Answers

You are not cancelling the submit action of the form so it will post back.

$("#submit-button").on('click', function (evt) {
    evt.preventDeafult();

Also when you make the Ajax call, you do nothing with the response.



This video can help you solving your question :)
By: admin