簡體   English   中英

在ASP.NET MVC中通過jQuery提交表單時傳遞參數

[英]Passing parameters when submitting a form via jQuery in ASP.NET MVC

我正在嘗試通過jQuery Ajax向我的控制器提交表單。 以下代碼大部分都有效,但是,ThreadId參數不會被傳遞。 如果我在不使用jQuery的情況下直接調用控制器,它會被傳遞,但是當使用jquery時,我在form.serialize()之后看不到ThreadId。 什么是將參數(如ThreadId)傳遞給jQuery表單帖子的最簡單方法?

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;
};

CONTROLLER

    [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");
        }

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;
});

另一種可能性是將表單內的ThreadId參數包含在隱藏字段中,而不是將其放在action屬性中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM