我的局部视图中有一个Ajax.BeginForm,但嵌套表单有问题,因此我想使用jquery脚本来替换Ajax.BeginForm并实现相同的结果。
这是我第一次使用的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
Submit.cshtml视图:
http://pastebin.com/GdKmK6V6
发布于 2016-04-19 05:40:38
您使用的是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()配料方法发送任何数据。您还没有展示该方法,但是假设它有一个参数string ingredient,则需要添加
data: { ingredient: $('#addingredient').val() },`添加到ajax函数
https://stackoverflow.com/questions/36704705
复制相似问题