问题
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