我的部分 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查看:
最佳答案
您正在调用 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/