Css view Model with Razor in asp.net mvc

2019-06-26 06:25发布

This is my view as a .css file,

@model StyleProfile

body {

color: @Model.color;
}

and I included this to my layout,

<link href="@Url.Action("CssDynamic")" rel="stylesheet" type="text/css" />

I have this in my controller

 public class HomeController : Controller
{
    private OnepageCMSEntities db = new OnepageCMSEntities();
    public ActionResult CssDynamic()
    {
        var model = db.StyleProfiles.FirstOrDefault();
        return new CssViewResult();
    }
}

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

It works fine. But I need to send a model to the view and the problem appears when I send a model object in the ActionMethod "CssDynamic"

 return new CssViewResult(model);

The error says

"this does not contain a constructor that takes 1 arguments.

How can I modify CssViewResult class to solve this problem?

2条回答
该账号已被封号
2楼-- · 2019-06-26 06:55

You missed the parameterized constructor for CssViewResult class. Add the following before ExecuteResult method in CssViewResult class.

    public CssViewResult(object model)
    {
        ViewData = new ViewDataDictionary(model);
    }

Also refer this stackoverflow post for the same.

How to set a model with a class that inherits partialviewresult

查看更多
地球回转人心会变
3楼-- · 2019-06-26 07:18

You should to create the constructor with appropriate argument like this:

    public class CssViewResult : PartialViewResult
    {
        private readonly object model;

        public CssViewResult(object model)
        {
            this.model = model;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            // Do something with this.model
            context.HttpContext.Response.ContentType = "text/css";
            base.ExecuteResult(context);
        }
    }
查看更多
登录 后发表回答