Add CSS references to page's <head> from a partial view

后端 未结 6 2361
感动是毒
感动是毒 2021-02-20 02:21

Is there a way to add CSS references to a page from a partial view, and have them render in the page\'s (as required by the HTML 4.01

6条回答
  •  难免孤独
    2021-02-20 02:47

    Another approach, which defeats the principles of MVC is to use a ViewModel and respond to the Init-event of your page to set the desired css/javascript (ie myViewModel.Css.Add(".css") and in your head render the content of the css-collection on your viewmodel.

    To do this you create a base viewmodel class that all your other models inherits from, ala

    public class BaseViewModel
    {
        public string Css { get; set; }
    }
    

    In your master-page you set it to use this viewmodel

    <%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
    

    and your head-section you can write out the value of the Css property

    
        <asp:ContentPlaceHolder ID="TitleContent" runat="server" />
        
    
        <%= Model.Css %>
    
    

    Now, in your partial view you need to have this code, which is kinda ugly in MVC

    
    

提交回复
热议问题