How to set a model with a class that inherits partialviewresult

半腔热情 提交于 2020-02-02 04:22:09

问题


I've based a dynamic css solution as mentioned here:

Dynamic CSS for ASP.NET MVC?

I notice the inherited PartialViewResult only has a getter for the Model, is there another way I can implement this functionality where HttpContext.Response.ContentType = "text/css" and I can send in a model like you can with a partialview?


回答1:


Simply adapt the custom action result so that it takes a model:

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

and then:

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

and in the view:

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


来源:https://stackoverflow.com/questions/10198546/how-to-set-a-model-with-a-class-that-inherits-partialviewresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!