Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax and Posting multiple complex objects to asp.net MVC Controller

`Greetings,

Having problem posting multiple parameters to an mc controller method.

controller...
[HttpPost]
public ActionResult SaveSomething(SomeDomainObject domainObject, bool anOption)
{
}

Ajax Code...
function performPostData(postDataOptions,closeWindow) {
        $.ajax({ type: postDataOptions.httpVerb,
            url: postDataOptions.url,
            datatype: "json",
            traditional: true,
            data: postDataOptions.data(),
            success: function () {
                if (closeWindow) {
                    var window = $('#window').data("kendoWindow");
                    window.close();             
                }
            },
            error: function (xhr, status, error) {
                var msg = JSON.parse(xhr.responseText);
                var validator = $("#editBase").kendoValidator().data("kendoValidator"),
                status = $(".editValidationStatus");
                var err = msg.Message;
                status.text(err).addClass("invalid");
            }
        });
    }

JScript function to format data...

function GetPostData()
{
    var _domainObject={            
            prop1: 1,
            prop2: 2,
            prop3: 3                      
        };
        return JSON.stringify({ domainObject:_domainObject,anOption: true});
}

I seeing in network capture that this is the request body:

{"domainObject":{"prop1":1,"prop2":2,"Prop3":3},"anOption":true}

The controller raises the following exception:

The parameters dictionary contains a null entry for parameter 'anOption' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult SaveSomething(Domain.Data.SomeDomainObject, Boolean)' in 'Reports.Controllers.TestController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I have been spinning my wheels for hours trying to get a simple domain object and another parameter of type bool to be serialized and passed to my controller. Any ideas?

like image 550
Ross Bush Avatar asked Nov 28 '12 03:11

Ross Bush


1 Answers

Looks like you are missing the content type parameter in the jquery ajax call. You should explicitly set it as json, as in this piece of code:

function performPostData(postDataOptions,closeWindow) {
    $.ajax({ type: postDataOptions.httpVerb,
        url: postDataOptions.url,
        datatype: "json",
        contentType: "application/json; charset=utf-8",

        ...rest of your code

Otherwise it will get its default value (see http://api.jquery.com/jQuery.ajax/):

application/x-www-form-urlencoded; charset=UTF-8

like image 58
Daniel J.G. Avatar answered Nov 12 '22 05:11

Daniel J.G.