【问题标题】:Css view Model with Razor in asp.net mvc在 asp.net mvc 中使用 Razor 的 Css 视图模型
【发布时间】:2015-07-07 07:45:53
【问题描述】:

这是我对.css 文件的看法,

@model StyleProfile

body {

color: @Model.color;
}

我将它包含在我的布局中,

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

我的控制器里有这个

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

它工作正常。但是我需要将模型发送到视图,当我在ActionMethod“CssDynamic”中发送模型对象时出现问题

 return new CssViewResult(model);

错误提示

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

如何修改CssViewResult类来解决这个问题?

【问题讨论】:

  • 为什么要将模型发送到视图并尝试将其作为 CSS 文件发送?你能提供一些关于你想要达到的目标的背景吗?可能有更好的方法。
  • 您在 CssViewResult 类中缺少一个构造函数。解释你到底想达到什么目标。
  • @HarveySpecter 我想 OP 想要使用来自PartialViewResult的默认构造函数
  • 可能,但显然不会工作,因为他需要 CssViewResult 的构造函数。
  • 我想用它来动态更改我的 css 文件。我需要将此模型对象发送到 ~/home/CssDynamic(强类型视图,即我的 css 文件)。

标签: c# css asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

您错过了 CssViewResult 类的参数化构造函数。在 CssViewResult 类的 ExecuteResult 方法前添加以下内容。

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

也可以参考这个 stackoverflow 帖子。

How to set a model with a class that inherits partialviewresult

【讨论】:

    【解决方案2】:

    您应该使用这样的适当参数创建构造函数:

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

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 2011-05-02
      相关资源
      最近更新 更多