C# 使用 jquery ajax 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16122949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit form with jquery ajax
提问by user2302622
I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success. my view:
我正在尝试学习 MVC,我想做的一件事是向我的控制器中的一个操作提交一个表单,这个操作将返回提交的数据。听起来很简单,但我已经尝试了几个小时没有任何成功。我的看法:
@using (Html.BeginForm("BlogComment","Blog"))
{
@Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
my controller:
我的控制器:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
and my js:
和我的js:
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '@Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
采纳答案by Idrees Khan
Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSONformat(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()
基本上你是直接传递 javascript 对象文字。因此,在将数据传递给控制器之前,它必须采用JSON格式(因为您已指定 application/json。请参阅您的 $.ajax 调用)。
所以,你缺少 JSON.stringify()
data: JSON.stringify({
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
}),
OR
或者
var someObj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
/// your other code
data: JSON.stringify(someObj),
// your rest of the code
});
回答by U.P
Instead of
代替
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
Try
尝试
$('form').submit(function () {
var obj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
...,
data: JSON.stringify(obj),
...,
});
return false;
});
You have to convert data to string before sending it to server. and JSON.stringifydoes that job
在将数据发送到服务器之前,您必须将数据转换为字符串。并JSON.stringify完成这项工作
回答by Moby's Stunt Double
You don't need to write any client side code to do this, FYI.
您不需要编写任何客户端代码来执行此操作,仅供参考。
To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:
要在 MVC 中成功使用 ajax 方法,您需要执行以下操作。将此键添加到 web.config 中的 appsettings:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As well as include the unobtrusive ajax script:
以及包括不显眼的ajax脚本:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm
然后在你的表单周围创建 div 容器并用 Ajax.BeginForm 替换 Html.BeginForm
<div id="ajaxReplace">
@using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
{
@Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
</div>
Then in your controller you'll return something like this:
然后在您的控制器中,您将返回如下内容:
return PartialView(ajaxComment);
This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,
这将节省您维护脚本以手动执行此操作,并将引导您按预期使用该框架。它还可以帮助您进行数据注释验证以及与之相关的所有有趣的东西,
I hope this helps in some way.
我希望这在某种程度上有所帮助。
回答by Bob Nowadly
Try this:
尝试这个:
The Model
该模型
public class Comment
{
public string CommentText { get; set; }
public DateTime? DateCreated { get; set; }
public long PostId { get; set; }
public string UserName { get; set; }
}
The View and js
视图和js
@model SubmitMvcForWithJQueryAjax.Models.Comment
@using (Html.BeginForm("BlogComment","Blog"))
{
@Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
@Html.EditorFor(m => m.UserName)
</div>
<div class="editor-text">
@Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
</div>
<div class="editor-field">
@Html.HiddenFor(m => m.DateCreated)
</div>
<div class="editor-field">
@Html.HiddenFor(m => m.PostId)
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var serializedForm = $(this).serialize();
$.ajax({
url: '@Url.Action("CommentForm")',
type: "POST",
data: serializedForm,
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
The Controller
控制器
public class CommentController : Controller
{
//
// GET: /Comment/
public ActionResult Index()
{
return View(new Comment());
}
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
//mRep.Add(ajaxComment);
//uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
}

