Styling your ASP.NET MVC application with a Razor CSS View Model

As a developer, I have my own perspective on a .css file.

@model StyleProfile

body {

color: @Model.color;
}

This code is included in my layout:

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

In my controller, I have the following setup:

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

Everything works smoothly. However, I encountered an issue when trying to pass a model object in the "CssDynamic" ActionMethod:

 return new CssViewResult(model);

An error message popped up saying:

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

To address this problem, what changes should be made to the CssViewResult class?

Answer №1

Don't forget to include the parameterized constructor for the CssViewResult class. Insert the following code snippet before the ExecuteResult method within the CssViewResult class:

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

For more information on this topic, you can also check out this post on Stack Overflow:

How to set a model with a class that inherits PartialViewResult

Answer №2

To implement the constructor, you will need to ensure that it receives the correct argument as shown in the example below:

    public class CustomCssView : PartialViewResult
    {
        private readonly object data;

        public CustomCssView(object data)
        {
            this.data = data;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            // Process the data in some way
            context.HttpContext.Response.ContentType = "text/css";
            base.ExecuteResult(context);
        }
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent scale animation for a specific section of the icon using CSS

I need help in preventing the scale animation of the :before part of the icon class from occurring when the button is hovered. The current behavior is causing the arrow to look distorted on hover... Link to the code on Codepen HTML <div class="se ...

Is there a way to show the time in a data table? Right now all it displays is "Obj obj

My data table is not displaying the correct information. Here is what my data table shows In my EmployeeSettings Controller, I am trying to retrieve data from the database table. However, I am encountering an error where it says "Cannot convert System.Ti ...

Creating a line that extends from the left side of the viewport to the full length of an element within a bootstrap column

I'm currently working on creating a title that has a unique design: https://i.sstatic.net/VhEBQ.png The design requires a horizontal line to start from the left side of the viewport and end at the same point where the title ends. I am aiming to keep ...

Managing Variants in SCSS with BEM Approach: A Comprehensive Guide

Trying to solve a frustrating issue with BEM can be quite the challenge. I currently use the BEM methodology for developing UI elements in my application. For example: <div class="card"> <h2 class="card__title">S ...

I'm curious if it's possible to create a scrolling marquee on an SVG path with the use of HTML and CSS?

I am interested in creating a unique effect similar to what is showcased on this website or in the main menu of Colin McRae Rally 2.0. My goal is to generate a path and animate text along it, with the letters wrapping around to the start as they reach the ...

Generating links in MVC Action Methods

In my controller, I have an action method that returns a JsonResult: public JsonResult GetDetails() { var rows = //Linq-To-SQL //Linq-To-Entities var lifts = (from r in rows group r by new { r.LiftID, r ...

Incorporating Anchors for Seamless Navigation in Menus

My website has various sections on the homepage and I want to add an anchor link to the navigation. This will allow users to scroll down to a specific section, like "About Us," when clicking on the appropriate nav link. I also need the anchor link to work ...

Troubleshooting in Visual Studio can be frustratingly sluggish

Starting up our extensive silverlight application is quite time-consuming due to the constant need for recompilation each time it launches. Even if everything has already been compiled, the process still occurs. The integration of RIA services in the pro ...

The Controller consistently receives a NULL value for the String variable passed from the View

I'm trying to send data from the View to the Controller using an Ajax call. However, the current code is passing NULL every time. Can someone please advise me on what I might be doing wrong? Here's the code in Index.cshtml: <input type="subm ...

influence the order in which dom elements are loaded when the site is loaded

I am seeking advice on how to control the loading sequence of elements in my website. The issue I am facing involves a curtain effect (a <div> with a background-image) overlaying my site, which triggers an animation function to remove it once the pag ...

Looping through rows and columns using ADO.NET data reader

I require assistance in developing a new logic. Consider the sample data provided below: Sample Data: Employee Table ID | Fname | Lname | Salary | DeptID --------------------------------------- 1 | John | Smith | 50000 | 1 2 | David | Robinson | 800 ...

Difficulty in fetching XML data through HTTP and saving it to a file

I have developed a simple scraper that connects to a PHP script on a remote server via HTTP and extracts XML data to save it into a local file. It's not exactly advanced programming, I know. Below is the code for the scraper (cleaned up and anonymiz ...

Combining Django Bootstrap input-group-addon with Model Form for seamless field integration

Currently, I am displaying my Django form in the following manner: <form action="/student/" method="post"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Launch" class="btn btn-primary"/> </form> I ha ...

Tips for maintaining the responsiveness of both images and text within a div container

I'm completely new to HTML and CSS. Everything looked perfectly aligned until I added text inside the three divs and now my images are unbalanced, even though I've set the same width and height: Here is the code snippet: #wrapper{ display:fl ...

In HTML, favoring the use of "//domain.com" over "https://domain.com" or "http://domain.com" is recommended for greater flexibility and compatibility

Related Questions: Changing all links to // Network-Path Reference URI / Scheme relative URLs I have noticed some websites using the following format: background:url(//cdn.domain.com/images/bg-normal.png) They utilize "//", which the browser aut ...

In what ways can a distant ancestor influence its subsequent generations down the line?

As a beginner utilizing Bootstrap v5, I am in the process of creating a navbar using the following HTML code. Within this code, the parent element (ul) of my link items contains a class called "navbar-nav" which results in my link items being styled to s ...

Managing a shared singleton object across multiple threads

I am facing a challenge where I need to access the same object from different threads, however, when I dispose of the object in one thread and try to resolve it in another thread, I end up with two different objects. The object should ideally be a singleto ...

Where can I locate documentation on the source code of Node Red Editor in order to customize the CSS and JS for the client?

I am seeking assistance in modifying the following files: red.min.js located at: ~ npm\node_modules\node-red\node_modules@node-red\editor-client\public\red style.min.css located at: ~ npm\node_modules\node-red\ ...

Mirror image navigation bar on both sides

Currently, I am attempting to create a navbar with images. The goal is to have the navbar centered in the middle with the image repeated on both sides. However, I am running into an issue where the picture is only repeating on the right side. Does anyone h ...

How can I retrieve the background and border color of the focused HTML element after pressing the tab on a website?

I am seeking to automate the process of conducting website accessibility checks by analyzing the color contrast between the focused element (after pressing tab) and its border color. Strategy: Initially, I attempted to take screenshots of the entire web ...