asp.net模型绑定成复杂类型

时间:2017-03-10 12:39:53

标签: c# asp.net model-binding

我试图简化一些代码。

我有一个返回数据的视图

<a class="btn btn-primary" href='@Url.Action("DownloadXls", "ArchivedMessages", new
                            {
                                Locations = string.Join(",", Model.SelectedLocations),
                                Machines = string.Join(",", Model.SelectedMachines),
                                Severities = string.Join(",", Model.SelectedSeverities),
                                Messages = string.Join(",", Model.SelectedMessages),
                                FromDate = Model.FromDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                                ToDate = Model.ToDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                                GroupMachines = Model.GroupMachines,
                                GroupMessages = Model.GroupMessages
                            })'>
    @Resources.ExportData
</a>

这会在我的控制器中调用以下方法

   public async Task<ActionResult> DownloadXls(List<int> Locations, List<int> Machines, List<int> Severities, List<int> Messages,
        bool GroupMachines, bool GroupMessages, DateTime FromDate, DateTime ToDate)
    {
        var reportData = await mediator.Send(new ArchivedMessagesExcelQuery
        {
            Locations = Locations,
            Machines = Machines,
            Severities = Severities,
            Messages = Messages,
            FromDate = FromDate,
            ToDate = ToDate,
            GroupMachines = GroupMachines,
            GroupMessages = GroupMessages
        });

        return File(reportData, "application/vnd.ms-excel", $"{DateTime.Now.ToShortDateString()}-data_export.xlsx");
    }

现在我想做的是简化这一切。由于数据直接进入对象初始化器。

我知道在ASP.net中可以使用这样的东西

public async Task<ActionResult> DownloadXls(ArchivedMessagesExcelQuery query)
{
    var reportData = await mediator.Send(query);
    return File(reportData, "application/vnd.ms-excel", $"{DateTime.Now.ToShortDateString()}-data_export.xlsx");
}
不幸的是,在我改变它之后,4列表的价值仍为空。

通过模型绑定器设置这些值

public class IntArrayModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (value == null) return new List<int>();

        var attempted = value.AttemptedValue;
        return attempted.Split(',').Select(int.Parse).ToList();
    }
}

但是为每个查询类型创建一个模型绑定器会给我更多代码然后保存。

有没有办法将此模型绑定器应用于所有字符串列表案例,即使它们在复杂类型中?

0 个答案:

没有答案