2016-08-15 99 views
0

我有一个选项供用户选择2日期范围之间的报告视图。将动态模型传递给局部视图

下面是我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将有值一样任何表1表2表3

如果用户选择任何即将生成的model将来自所有3个表格,因此模型的结构将基于用户选择。我将如何产生model为此并将其传递到PartialView?它会是一组Key/Value对还是应该dynamic在这里使用?无论如何要达到上述要求的报告结构?

+0

如果模型不同,为什么不为每个模型不同的部分? –

+0

像4种不同的部分视图? @StephenMuecke –

+1

是的,并在控制器方法 - “if(ReportFor =”Any“){var model = ...;返回PartialView(“_ AnyReport,model);)else if(ReportFor =”Table1“){var model = ...; return PartialView(”_ Table1Report“,model);)etc'(但建议您使用enum作为' ReportFor' values) –

回答

1

一般情况下,请避免使用dynamic。您会失去编译时检查,智能感知以及在视图中使用***For()方法的能力(lambda表达式不支持动态对象)。

改为使用强类型并为每个报表创建视图模型。假定会有一些通用的属性,然后用碱模型

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

,然后为每一个模型中的强类型化的局部视图开始,例如_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 (.... 
+0

谢谢斯蒂芬..这很有道理.. :) –

相关问题