代码之家  ›  专栏  ›  技术社区  ›  Prabhu

在ASP.NET MVC中通过jQuery提交表单时传递参数

  •  1
  • Prabhu  · 技术社区  · 15 年前

    ASPX公司

    <% Html.BeginForm("AddComment", "Home", new { ThreadId = Model.Id },
       FormMethod.Post, new { @id = "AddComment" + Model.Id.ToString(),
       @onsubmit = "javascript:AddComment(this);return false" }); %>
    <%: Html.TextBox("CommentText", "", new { @class = "comment-textbox" })%>
    <input id="Comment" type="submit" name="submitButton" value="Post Comment" />   
    <% Html.EndForm(); %>
    

    JavaScript

        AddComment = function (sender) {
        var form = $(sender);
        var data = form.serialize();
        $.ajax({
            type: "POST",
            url: "/Home/AddComment",
            data: data,
            dataType: "html",
            success: function (response) {
                alert(response);
            },
            error: function (error) {
                alert(error);
            }
        });
        return false;
    };
    

        [HttpPost]
            public ActionResult AddComment(string submitButton, Comment comment)
            {
                comment.CreatedDate = DateTime.Now;
                comment.PosterId = LoggedInUser.Id;
    
                _repository.AddComment(comment);
                _repository.Save();
    
                if (Request.IsAjaxRequest())
                {
                    return View("Comment", comment);
                }
                else
                    return RedirectToAction("Index");
            }
    
    1 回复  |  直到 15 年前
        1
  •  4
  •   Darin Dimitrov    15 年前

    这个 ThreadId 参数包含在 action /Home/AddComment 不再提供这个参数。您可以执行以下操作将其ajaxify:

    $('#idofyourform').submit(function() {
        $.ajax({
            // use the method as defined in the <form method="POST" ... 
            type: this.method,
    
            // use the action as defined in <form action="/Home/AddComment?ThreadId=123"
            url: this.action,
    
            data: $(this).serialize(),
            dataType: 'html',
            success: function (response) {
                alert(response);
            },
            error: function (error) {
                alert(error);
            }
        });
        return false;
    });
    

    另一种可能是包括 螺纹 如果将窗体内的参数放入action属性中,则将其改为隐藏字段。