Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Ajax.BeginForm with jquery script

I had an Ajax.BeginForm in my partial view but had issues with a nested form, for this reason I would like to use a jquery script to replace the Ajax.BeginForm and achieve tesame result.

This was the Ajax.BeginForm I used first:

@using (Ajax.BeginForm("CreateIngredient", "Recipe", new AjaxOptions() { UpdateTargetId = "create-ingredient", HttpMethod = "Post", OnComplete = "ClearTextboxes" }, new { @id = "createIngredient" }))
{
    @Html.LabelFor(model => model.Ingredients, "Custom Ingredient")
    @Html.TextBoxFor(model => model.addIngredient, new { @id = "addIngredient" })
    <input type="submit" id="createButton" value="Create" class="default-btn small-button light-border" onclick="$('#SelectedIngredient').append('<option>' + $('#addIngredient').val() + '</option>')" />
}

I have tried this script:

<script type="text/javascript">
function ClearTextboxes() {
    document.getElementById('addIngredient').value = ''
}

$(function () {
    $("#createButton").click(function () {
        $.ajax({
            type: "POST",
            url: "/Recipe/CreateIngredient",
            success: function (data) {
                $('#result').html(data);
            }
        });
    });
});

But when clicking on the button it goes to the SubmitRecipe HttpPost instead of the CreateIngredient HttpPost

Submit.cshtml View:

http://pastebin.com/GdKmK6V6

like image 907
josephzigler Avatar asked Mar 01 '26 08:03

josephzigler


1 Answers

You are hitting the CreateIngredient() method, but because you have not cancelled the default submit, you are also hitting the SubmitRecipe().

Change the button to

<input type="button" id="createButton" .... 

so it no longer submits the parent form, or cancel the default action

$("#createButton").click(function () {
    $.ajax({
        type: "POST",
        url: '@Url.Action("CreateIngredient", "Recipe")', // use Url.Action()
        success: function (data) {
            $('#result').html(data);
        }
    });
    return false; // add this
});

Note that you have nested forms which is invalid html and you need to move the inner form to below the outer form. Your also not sending any data to the CreateIngredient() ingredient method. You have not shown the method, but assuming it has a paramater string ingredient, you would need to add

data: { ingredient: $('#addingredient').val() },`

to the ajax function