我知道这个问题已经在Stakoverflow中被问过多次了,但是没有一个解决方案对我有帮助。有人可以告诉我做错了什么吗
我有一个如下的控制器动作
<HttpPost()>
Function WFUserEdited(ByVal userdetails As userdetails) As ActionResult
Return View()
End Function
我的Viewmodel如下所示
Public Class userdetails
Public Property Username As String
Public Property Password As String
Public Property Fullname As String
Public Property Location As String
Public Property Appcode As String
Public Property Userlevel As String
End Class
我的Jquery Ajax调用如下所示
$("#btnSubmit").click(function () {
var q = validate();
if (q = true) {
var userdetails = {};
userdetails.UserName = $('#txtusername').val().toString();
userdetails.Password = $('#txtPassword').val().toString();
userdetails.Fullname = $('#txtfullName').val().toString();
userdetails.Location = $('#txt_location').val().toString();
userdetails.Appcode = $("#drp_appcode").chosen().val().toString();
userdetails.Userlevel = $("#drp_userlevel").chosen().val().toString();
userdetails = JSON.stringify(userdetails);
var url = '@Url.Action("WFUserEdited", "WFUser")';
$.ajax({
url: url,
type: 'POST',
traditional: false,
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: { "userdetails": userdetails },
success: function (data) {
},
error: function (data) {
}
});
}
});
});
在The Beginexecutecore iam上,出现以下异常
Protected Overrides Function BeginExecuteCore(callback As AsyncCallback, state As Object) As IAsyncResult
Try
ViewBag.UserImage = "http://_layouts/15/CaptarisWFTasksWebPart/EmployeeImages/sree.jpg"
Catch generatedExceptionName As Exception
Return MyBase.BeginExecuteCore(callback, state)
End Try
Return MyBase.BeginExecuteCore(callback, state)
End Function
System.Web.Mvc.dll中发生类型为'System.ArgumentException'的异常,但未在用户代码中处理 附加信息:无效的JSON原语:userdetails。
答案 0 :(得分:2)
当您指定contentType: "application/json
时,必须将以JSON格式发送的数据字符串化。在您的情况下,数据是javascript objec`(其中包含一些字符串化数据),而不是JSON。
由于userdetails
已被字符串化(使用JSON.stringify()
),因此将ajax代码更改为
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: userdetails,
success: function (data) {
...
});
但是,不需要将其作为JSON发送。您可以使用默认的'application/x-www-form-urlencoded; charset=UTF-8'
删除userdetails = JSON.stringify(userdetails);
行代码,然后删除
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: userdetails,
success: function (data) {
...
});
请注意,在两种情况下,您都可以省略traditional: false
选项。
并且如果您已经使用HtmlHelper
方法正确地生成了表单控件来绑定到模型属性,那么就不需要手动创建object
。您可以简单地使用.serialize()
。此外,您应该处理表单提交事件,而不是按钮单击事件,并检查.valid()
$('form').submit(function(e) {
e.preventDefault();
if (!$(this).valid()) {
return;
}
var userdetails = $(this).serialize();
var url = '@Url.Action("WFUserEdited", "WFUser")';
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: userdetails,
success: function (data) {
...
});
});