Invalid JSON primitive On Post

Viewed 1845

I know this question has been asked multiple times in Stakoverflow.But none of the solution is helping me .Can anyone tell me what had been done wrong

I have a Controller Action as below

<HttpPost()>
    Function WFUserEdited(ByVal userdetails As userdetails) As ActionResult
            Return View()
    End Function

And My Viewmodel is like below

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

And My Jquery Ajax call is like below

 $("#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) {
                        }
                    });
                }
            });
        });

And at The Beginexecutecore iam getting the below exception

 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

An exception of type 'System.ArgumentException' occurred in System.Web.Mvc.dll but was not handled in user code Additional information: Invalid JSON primitive: userdetails.

1 Answers

When your specify contentType: "application/json, you must stringify the data you send as JSON. In your case, the data is a javascript objec` (which contains some stringified data), not JSON.

Since userdetails is already stringified (using JSON.stringify()), then change the ajax code to

$.ajax({
    url: url,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: userdetails,
    success: function (data) {
        ...
});

However, there is no need to send it as JSON. You can use the default 'application/x-www-form-urlencoded; charset=UTF-8'

Delete the userdetails = JSON.stringify(userdetails); line of code, and then its just

$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    data: userdetails,
    success: function (data) {
        ...
});

Note in both cases, you can omit the traditional: false option.

And if you have generated your form controls correctly using the HtmlHelper methods to bind to your model properties, then you do not need to manually create the object. You can simply use .serialize(). In addition, you should be handling the forms submit event, not the button click event, and checking .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) {
            ...
    });
});
Related