【问题标题】:How to set a model with a class that inherits partialviewresult如何使用继承 partialviewresult 的类设置模型
【发布时间】:2012-04-18 13:59:06
【问题描述】:

我基于此处提到的动态 css 解决方案:

Dynamic CSS for ASP.NET MVC?

我注意到继承的 PartialViewResult 只有一个模型的 getter,有没有另一种方法可以实现这个功能,其中 HttpContext.Response.ContentType = "text/css" 并且我可以像使用部分视图一样发送模型?

【问题讨论】:

    标签: asp.net-mvc razor


    【解决方案1】:

    只需调整自定义操作结果,使其采用模型:

    public class CssViewResult : PartialViewResult
    {
        public CssViewResult(object model)
        {
            ViewData = new ViewDataDictionary(model);
        }
    
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.ContentType = "text/css";
            base.ExecuteResult(context);
        }
    }
    

    然后:

    public ActionResult Css()
    {
        MyViewModel model = ...
        return new CssViewResult(model);
     }
    

    在视图中:

    @model MyViewModel
    @{
        var color = "White";
        if (Model.Hour > 18 || Model.Hour < 8)
        {
            color = "Black";
        }
    }
    .foo {
        color: @color;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-17
      • 2017-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 2012-08-01
      • 1970-01-01
      • 2020-06-26
      相关资源
      最近更新 更多