小编典典

MVC3和JSON.stringify()ModelBinding返回空模型

json

我正在尝试使用MVC3和JSON进行模型绑定,但是运气不佳…不管我做什么,我似乎都null在服务器上获取模型。

方法签名:

public ActionResult FilterReports(DealSummaryComparisonViewModel model)

Javascript已 更新

<script type="text/javascript" language="javascript">

    $(document).ready(function () {
        $('#filter-reports').click(filterReports);
    });

    function filterReports() {
        var filters = {
            SelectedRtoId: $('#SelectedRtoId').val(),
            SelectedPricingPointId: $('#SelectedPricingPointId').val(),
            SelectedLoadTypeId: $('#SelectedLoadTypeId').val(),
            SelectedBlockId: $('#SelectedBlockId').val(),
            SelectedRevisionStatusId: $('#SelectedRevisionStatusId').val()
        }
        var dealSummaries = { SelectedItemIds: $('#SelectedItemIds').val() }
        var model = { ReportingFilters: filters, DealSummaries: dealSummaries }

        $('#selected-items select option').attr("selected", "selected");
        $.ajax({
            url: '@Url.Action("FilterReports")',
            data: model,
            contentType: 'application/json',
            dataType: 'json',
            success: function (data) {
                alert(data);
            }
        }); 
    }
</script>

楷模:

public class DealSummaryComparisonViewModel
{
    public ReportingFiltersViewModel ReportingFilters { get; set; }
    public LadderListViewModel DealSummaries { get; set; }
}

public class LadderListViewModel
{
    public MultiSelectList AvailableItems { get; set; }

    public int[] SelectedItemIds { get; set; }
    public MultiSelectList SelectedItems { get; set; }
}

public class ReportingFiltersViewModel
{
    public int? SelectedRtoId { get; set; }
    public ICollection<Rto> Rtos { get; set; }

    public int? SelectedPricingPointId { get; set; }
    public ICollection<PricingPoint> PricingPoints { get; set; }

    public int? SelectedLoadTypeId { get; set; }
    public ICollection<LoadType> LoadTypes { get; set; }

    public int? SelectedBlockId { get; set; }
    public ICollection<Block> Blocks { get; set; }

    public int? SelectedRevisionStatusId { get; set; }
    public ICollection<RevisionStatus> RevisionStatuses { get; set; }

    public bool? DealStatus { get; set; }
}

该模型在客户端看起来不错:

{"ReportingFilters":{
    "SelectedRtoId":"5",
    "SelectedPricingPointId":"20",
    "SelectedLoadTypeId":"55",
    "SelectedBlockId":"21",
    "SelectedRevisionStatusId":"11" 
},"DealSummaries":{
    "SelectedItemIds":["21","22","23","24","25"] 
}}

那为什么我什么也没回到控制器上呢?在过去的两天里,这一直给我带来麻烦,请帮忙!谢谢!!

更新
我已经将我的javascript部分更新为我当前正在使用的部分。现在,此部分将模型与ReportingFilers和DealSummaries对象一起返回给控制器,但是其中的所有值均为null。

它可能与字符串值有关吗?如果是这样,我该如何解决?


阅读 287

收藏
2020-07-27

共1个答案

小编典典

将$ .getJSON行更改为:

$.ajax({ 
   url: '@Url.Action("FilterReports")',
   data: JSON.stringify(viewModel),
   contentType: 'application/json',
   dataType: 'json',
   success: function (data) { alert(data); }
});

这样,MVC知道它正在接收JSON,并将其正确绑定到模型。

2020-07-27