jquery - 用 jquery 脚本替换 Ajax.BeginForm

标签 jquery ajax asp.net-mvc-4

我的部分 View 中有一个 Ajax.BeginForm,但嵌套表单有问题,因此我想使用 jquery 脚本来替换 Ajax.BeginForm 并实现 tesame 结果。

这是我首先使用的 Ajax.BeginForm:

@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>')" />
}

我尝试过这个脚本:

<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);
            }
        });
    });
});

但是当单击按钮时,它会转到 SubmitRecipe HttpPost 而不是 CreateIngredient HttpPost

提交.cshtml查看:

http://pastebin.com/GdKmK6V6

最佳答案

您正在调用 CreateIngredient() 方法,但由于您尚未取消默认提交,因此您还将调用 SubmitRecipe()

将按钮更改为

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

因此不再提交父表单,或者取消默认操作

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

请注意,您的嵌套表单是无效的 html,您需要将内部表单移至外部表单下方。您也没有向 CreateIngredient() 成分方法发送任何数据。您尚未显示该方法,但假设它有一个参数字符串成分,您需要添加

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

到ajax函数

关于jquery - 用 jquery 脚本替换 Ajax.BeginForm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36704705/

相关文章:

javascript - 是否可以在 for 循环中设置 span 上唯一的第一个元素?

javascript - JQuery - AJAX load() 方法帮助

javascript - 在 javaScript 动态添加一些标签到我的 HTML 之后我的设计改变了,我该如何解决这个问题

javascript - 将时间戳从 24 小时更改为 12 小时并通过 jQuery 追加

javascript - 带有 curl 短信的 php 在实时服务器上发送

javascript - 每 30 秒运行一次 ajax 并显示倒数计时器

jquery - MVC 中使用 Knockout 进行文件上传

.net - 如何防止类中的属性不存储在 session 中

asp.net-mvc-4 - MVC4 WebApi OData Delta<T> 未填充 GUID 或 Int 字段

jquery - 仅运行一次 window.addEventListener 函数