5

`你好,

将多个参数发布到 mc 控制器方法时出现问题。

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});
}

我在网络捕获中看到这是请求正文:

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

控制器引发以下异常:

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

我已经旋转了好几个小时,试图获取一个简单的域对象和另一个 bool 类型的参数来序列化并传递给我的控制器。有任何想法吗?

4

1 回答 1

5

看起来您在 jquery ajax 调用中缺少内容类型参数。您应该将其显式设置为 json,如以下代码所示:

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

        ...rest of your code

否则它将获得其默认值(请参阅http://api.jquery.com/jQuery.ajax/):

应用程序/x-www-form-urlencoded;字符集=UTF-8

于 2012-11-29T19:54:43.920 回答