Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a model with a class that inherits partialviewresult

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?

like image 289
FiveTools Avatar asked Jan 16 '23 22:01

FiveTools


1 Answers

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;
}
like image 184
Darin Dimitrov Avatar answered Jan 31 '23 01:01

Darin Dimitrov