从视图中检索操作方法属性

时间:2012-08-11 16:14:06

标签: c# asp.net-mvc-3 razor attributes

假设我在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");
}

在我的剃刀视图中,我希望能够说出来:

  1. PageOptions属性是否附加到调用操作方法。
  2. 如果是,则其OutputFormat属性的值是什么。
  3. 这里有一些伪代码,说明了我尝试做的事情:

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

    这可能吗?

2 个答案:

答案 0 :(得分:2)

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

只需创建一个枚举

public enum OutputFormatType {
    Web
    PDF
}

并在ViewModel中使用它

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

然后在Controller操作中分配值

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);
}

答案 1 :(得分:1)

我想添加AlfalfaStrange's answer控制器的操作不应该知道附加到它的属性。这意味着这些属性实际上应该是拦截OnResultExecuting的动作过滤器,并将此数据注入ViewData中的一个众所周知的位置。