简体   繁体   中英

Passing dynamic model to partial view

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

Below is my 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; }
}

Now ReportForList will have values like Any , Table1 , Table2 , Table3 .

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?

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
}

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

@model Report1 // or IEnumerable<Report1>

and in the controller method

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 (....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM