我正在尝试通过 jQuery Ajax 将表单提交到我的 Controller 。下面的代码大部分工作,但是,ThreadId 参数没有得到传递。如果我不使用 jQuery 直接调用 Controller ,它就会通过,但是当使用 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
属性中。当您对此表单进行 ajax 化时,您将发布到 /Home/AddComment
并且不再提供此参数。您可以执行以下操作来对其进行 ajax 化:
$('#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 属性中。
关于c# - 在 ASP.NET MVC 中通过 jQuery 提交表单时传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005639/