1

假设我在 MVC3 控制器中有以下三个操作方法:

public ActionResult ShowReport()
{
    return View("ShowReport");
}

[PageOptions(OutputFormat = OutputFormat.Web)]
public ActionResult ShowReportForWeb()
{
    return View("ShowReport");
}

[PageOptions(OutputFormat = OutputFormat.Pdf)]
public ActionResult ShowReportForPdf()
{
    return View("ShowReport");
}

在我的 Razor 视图中,我希望能够告诉您:

  1. PageOptions 属性是否附加到调用操作方法。
  2. 如果是,它的 OutputFormat 属性的值是多少。

这是一些伪代码,说明了我正在尝试做的事情:

@if (pageOptions != null && pageOptions.OutputFormat == OutputFormat.Pdf)
{
@:This info should only appear in a PDF.
} 

这可能吗?

4

2 回答 2

2

LeffeBrune 是正确的,您应该将该值作为 ViewModel 的一部分传递

只需创建一个枚举

public enum OutputFormatType {
    Web
    PDF
}

并在您的 ViewModel 中使用它

public class MyViewModel {
    ...
    public OutputFormatType OutputFormatter { get; set; }
}

然后在您的控制器操作中分配值

public ActionResult ShowReportForWeb()
{
    var model = new MyViewModel { OutputFormatter = OutputFormatType.Web };
    return View("ShowReport", model);
}

public ActionResult ShowReportForPdf()
{
    var model = new MyViewModel { OutputFormatter = OutputFormatType.PDF };
    return View("ShowReport", model);
}

public ActionResult ShowReport(MyViewModel model)
{
    return View(model);
}
于 2012-08-11T18:06:50.633 回答
1

我想在AlfalfaStrange 的回答中补充一点,控制器的操作不应该知道附加到它的属性。这意味着这些属性实际上应该是动作过滤器,它们拦截OnResultExecuting这些数据并将其注入ViewData.

于 2012-08-11T20:00:51.827 回答