gpt4 book ai didi

asp.net-mvc - 以编程方式提交和 MVC Ajax 表单时如何定位 div?

转载 作者:行者123 更新时间:2023-12-02 00:09:07 26 4
gpt4 key购买 nike

我在表单上使用 MVC4 Ajax 辅助函数,我想从脚本提交表单。

问题是当我调用提交函数时,它没有加载到正确的 div 中。有什么想法吗?

@using (Ajax.BeginForm("NewGame", "Home", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "targetDiv" }, new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
<a class=button onclick="$('#newGameForm').submit();">New Game</a>
}

单击标准提交按钮将调用结果加载到 targetDiv 中。单击 anchor 将替换当前的 div。

最佳答案

关键是通过.preventDefault()防止默认浏览器行为return false在事件处理程序的末尾。

我会这样做:

<div id="targetDiv"></div>
@using(Html.BeginForm("NewGame", "Home", FormMethod.Post,
new { id = "newGameForm" }))
{
<input type="hidden" name="client_seed" id="client_seed" />
<input type="submit" value="New Game" id="NewGameButton" />
}

<script type="text/javascript">
$(document).ready(function () {
$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
data: $(this).serialize(),
type: $(this).attr("method") // "POST"
})
.done(function(result) {
$("#targetDiv").html(result);
})
.fail(function((jqXHR, textStatus, errorThrown) {
// handle error
});
});
});
</script>

如果你坚持使用 anchor <a> ...

<a href="#" class="button" id="submit-link">New Game</a>

<script type="text/javascript">
$(document).ready(function() {
$("#submit-link").on("click", function(e) {
e.preventDefault();
$("#newGameForm").submit();
});

$("#newGameForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
...
});
});
</script>

编辑 还有一个AjaxHelper.ActionLink方法。如果您已经在使用 AjaxHelper在代码的其他部分,您可能希望坚持使用它。

关于asp.net-mvc - 以编程方式提交和 MVC Ajax 表单时如何定位 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16502233/

26 4 0
文章推荐: mathjax - 如何以编程方式将 MathJax LaTeX 格式应用于
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com