【问题标题】:How do I target a div when programmatically submitting and MVC Ajax form?以编程方式提交和 MVC Ajax 表单时如何定位 div?
【发布时间】:2013-05-11 22:15:59
【问题描述】:

我在表单上使用 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。单击锚点会替换当前的 div。

【问题讨论】:

    标签: asp.net-mvc asp.net-ajax


    【解决方案1】:

    关键是通过事件处理程序末尾的.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>
    

    如果你坚持使用锚&lt;a&gt;...

    <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,您可能希望坚持使用它。

    【讨论】:

      【解决方案2】:

      伪代码。

      <a class=button onclick="PostAjax();">New Game</a>
      
      function PostAjax(){
          $.ajax({
              url:"Home/NewGame",
              data:$('#newGameForm').serialize(),
              DataType:"HTML", // assuming your post method returns HTML
              success:function(data){
                  $("#targetDiv").html(data);
              },
              error:function(err){
                  alert(err);
              }
          })
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-03
        • 2010-11-22
        • 1970-01-01
        • 2018-06-13
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 2014-07-11
        相关资源
        最近更新 更多