Skip to main content
 首页 » 编程设计

c#之无法将参数作为 JSON 传递给 mvc Controller

2024年02月13日14qq号

我试图将一个 id 和一个具有四个属性的 object 传递给 Action Controller ,但不幸的是它没有通过,我收到以下错误。

The parameters dictionary contains a null entry for parameter 'batchID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.JsonResult GetItems(Int32, Ebiquity.Reputation.Neptune.Web.Models.MyWorkFilterModel)' in 'Ebiquity.Reputation.Neptune.Web.Controllers.MyWorkController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

传递的 JSON 是:

{ 
    "batchID": 21610, 
    "filter": 
    { 
        "issueNo": "1", 
        "messageNo": "2", 
        "itemDate": "Wed, 05 Feb 2014 00:00:00 GMT", 
        "mediaName":"3" 
    } 
}; 

ajax调用:

self.GetItems = function (batchID, issueNo, messageNo, itemDate, mediaName) { 
 
    var filter = { 
        issueNo: issueNo, 
        messageNo: messageNo, 
        itemDate: itemDate, 
        mediaName: mediaName 
    }; 
         
    $.ajax({ 
        type: "GET", 
        url: "/MyWork/GetItems", 
        data: JSON.stringify({ 
            batchID: batchID, 
            filter: filter 
        }), 
        dataType: "json", 
        success: function (result) { 
 
            self.Items([]); 
            if (result.Items != null) { 
                var tempItems = ko.mapping.fromJS(result.Items, mappingOptions); 
                self.Items.push.apply(self.Items, tempItems()); 
            } 
        } 
    }); 
}; 

Controller :

[HttpGet] 
public JsonResult GetItems(int batchID, MyWorkFilterModel filter) 
{ 
    using (var rep = new WorkRepository(CurrentUser)) 
    { 
        return Json(rep.GetBatch(batchID, filter), JsonRequestBehavior.AllowGet); 
    } 
} 

过滤器模型:

public class MyWorkFilterModel 
{ 
    public int? IssueNo { get; set; } 
    public int? MessageNo { get; set; } 
    public string MediaName { get; set; } 
    public DateTime? ItemDate { get; set; } 
} 

请您参考如下方法:

您必须将 AJAX 调用的类型更改为 POST 而不是 GET。数据参数不会随 GET 请求一起发送。