How to set a model with a class that inherits part

2019-05-15 05:08发布

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条回答
SAY GOODBYE
2楼-- · 2019-05-15 05:42

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;
}
查看更多
登录 后发表回答