首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用jquery脚本替换Ajax.BeginForm

用jquery脚本替换Ajax.BeginForm
EN

Stack Overflow用户
提问于 2016-04-19 05:34:23
回答 1查看 658关注 0票数 3

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

这是我第一次使用的Ajax.BeginForm:

代码语言:javascript
复制
@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>')" />
}

我已经尝试过这个脚本:

代码语言:javascript
复制
<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

Submit.cshtml视图:

http://pastebin.com/GdKmK6V6

EN

回答 1

Stack Overflow用户

发布于 2016-04-19 05:40:38

您使用的是CreateIngredient()方法,但是因为您没有取消默认的提交,所以您也使用了SubmitRecipe()

将按钮更改为

代码语言:javascript
复制
<input type="button" id="createButton" .... 

因此,它不再提交父窗体,或取消默认操作

代码语言:javascript
复制
$("#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()配料方法发送任何数据。您还没有展示该方法,但是假设它有一个参数string ingredient,则需要添加

代码语言:javascript
复制
data: { ingredient: $('#addingredient').val() },`

添加到ajax函数

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36704705

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档