将动态模型传递到局部视图 [英] Passing dynamic model to partial view

查看:80
本文介绍了将动态模型传递到局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个选项供用户选择2个日期范围之间的报告视图.

I have an option for user to select the reporting view between 2 date range.

下面是我的 ReportsViewModel.cs

public class ReportsViewModel
{
    public DateTime DateRangeFrom { get; set; }
    public DateTime DateRangeTo { get; set; }
    public string ReportFor { get; set; }
    public SelectList ReportForList { get; set; }
}

现在 ReportForList 的值将为 Any Table1 Table2 Table3 .

如果用户选择任何,将要生成的模型将来自所有3个表,因此模型的结构将基于用户选择.我将如何为此生成 model 并将其传递给 PartialView ?它是一组 Key/Value 对还是在此处使用 dynamic ?无论如何,是否可以实现上述要求的报告结构?

If user selects Any the model that is going to get generated will be from all the 3 tables and so and hence the structure of the model will be based on user selection. How would I go generating model for this and pass it into PartialView? Will it be a set of Key/Value pairs or should dynamic be used here? Is there anyway to achieve the reporting structure for above requirement?

推荐答案

通常,避免使用 dynamic .您将失去编译时检查,智能感知能力以及在视图中使用 *** For()方法的能力(lambda表达式不支持动态对象).

Generally, avoid using dynamic. You lose compile-time checking, intellisense and the ability to use the ***For() methods in your view (lambda expressions do not support dynamic objects).

相反,请使用强类型并为每个报表创建一个视图模型.假设会有一些共同的属性,然后从基本模型开始

Instead use strong types and create a view model for each report. Assuming there will be some common properties, then start with a base model

public abstract class ReportBase
{
    .... // common properties
}
public class Report1 : ReportBase
{
    .... // properties specific table 1
}
public class Report2 : ReportBase
{
    .... // properties specific table 2
}

,然后为每个模型创建强类型的局部视图,例如 _Report1.cshtml

and then create strong typed partial views for each model, for example _Report1.cshtml

@model Report1 // or IEnumerable<Report1>

和控制器方法

public PartialViewResult ShowReport(ReportsViewModel model)
{
    if (model.ReportFor == "Table1")
    {
        Report1 report = .... // your query to generate data
        return PartialView("_Report1", report);
    }
    else if (model.ReportFor == "Table2")
    {
        Report2 report = .... // your query to generate data
        return PartialView("_Report2", report);
    }
    else if (....

这篇关于将动态模型传递到局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆