Css view Model with Razor in asp.net mvc

前提是你 提交于 2019-12-23 12:38:45

问题


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?


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/29919754/css-view-model-with-razor-in-asp-net-mvc

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