【发布时间】:2011-06-30 15:05:56
【问题描述】:
我正在尝试使用 jQuery 的 $.ajax() 函数将表单变量发布到 MVC 路由。问题是,当代码执行我的 MVC 操作时,所有参数都为空,即使数据正在传递给它们:
jQuery:
$(function () {
$('#signupform').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
var postData = '{name : "' + $("#Name").val() + '", email : "' + $("#Email").val() + '", message : "' + $("#Message").val() + '" }';
$.ajax({
url: "/api/contact-form-post",
data: postData,
type: "get"
})
.complete(function (data) {
$("#formContainer").html($("#formThankYou").html());
});
}
});
});
调用 alert(postData) 输出如下:
{name : "Scott Smith", email : "scott@smith.com", message : "test message" }
MVC 动作:
public JsonResult ContactFormPost(string email, string name = "" , string message = "")
{
AddEmailToMailingList(email);
if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(message))
{
InsertContactMessage(email, name, message);
}
return Json(true);
}
使用 FireBug 检查请求会发现这是被调用的 URL。显然url参数格式不正确,但我不知道为什么。
http://localhost:10637/api/contact-form-post?{name%20:%20%22Scott%20Smith%22,%20email%20:%20%22scott@smith.com%22,%20message%20:%20%22Test%20message%22 %20}
我是否在这里犯了任何明显的错误,导致我的 ContactFormPost 方法的参数始终为空?
【问题讨论】:
标签: c# jquery asp.net-mvc ajax json