Reputation: 36068
In each of my views, I am constantly adding a style and script associated with the view. It is convention in the application we introduced, but we want to automatically apply this convention instead.
Currently our views look like this:
<p>This is the view!</p>
@section styles {
<link rel="stylesheet" href="~/Views/Home/Index.css" />
}
@section scripts {
<script src="~/Views/Home/Index.js"></script>
}
Is there a way to automate adding the styles and scripts? Perhaps in the base class of the controller, such as:
public class BaseController : Controller
{
string controller = RouteData.Values["controller"].ToString();
string action = RouteData.Values["action"].ToString();
string script = string.Format("<script src=\"~/Views/{0}/{1}.js\"></script>", controller, action);
string style = string.Format("<link rel=\"stylesheet\" href=\"~/Views/{0}/{1}.css\" />", controller, action);
// Todo: How to add script and style to sections programmatically???
}
Upvotes: 0
Views: 947
Reputation: 239220
You can use the controller/action name values in your views, and specifically, in your layout. Just edit your layout and in the head add:
<link rel="stylesheet" href="~/Views/@(ViewContext.RouteData.Values["controller"])/@(ViewContext.RouteData.Values["action"]).css" />
And before your closing body tag, add:
<script src="~/Views/@(ViewContext.RouteData.Values["controller"])/@(ViewContext.RouteData.Values["action"]).js"></script>
Upvotes: 2