Add css, js or other content to a views head from partial views - asp.net-mvc-4

I have found a few questions relating to this, but generally there are many different answers and they all seem very messy and complex.
If that is what needs to be done, then ok i better sit down and tackle it.
I want to know what the simplest and most efficient way is to add content to your head from partial views.
Reason I need to do this is i need certain java script and jquery on each page and it differs from page to page. I donot just want to add them all in the _layout view.

You can do this with sections. For example:
I have more than two view which each other has same _Layout.My Index action in Company Controller has a sections as follow:
#model Invoice.Model.HelperClasses.CompanyViewModel
#{
ViewBag.Title = "Companies";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section usage{
<link href="~/css/uniform.default.css" rel="stylesheet" />
}
#section other{
<link href="~/css/datepicker.css" rel="stylesheet" />
<link href="~/css/SimpleSlide.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
}
#section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
}
and Display Action in Invoice controller has same sections but different css and js as follow:
#model Invoice.Model.HelperClasses.InvoiceViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section usage{
#*<link href="~/css/uniform.default.css" rel="stylesheet" />*#
}
#section other{
<link href="~/css/DT_bootstrap.css" rel="stylesheet" />
<link href="~/css/responsive-tables.css" rel="stylesheet" />
<script src="~/js/datatables/extras/ZeroClipboard.js"></script>
}
#section script
{
<script src="~/js/datepicker/bootstrap-datepicker.js"></script>
<script src="~/js/validate/jquery.metadata.js"></script>
<script src="~/js/validate/jquery.validate.js"></script>
}
and then you can use this section in _Layout but its required argument should be false. Look at:
<!DOCTYPE html>
<html>
<head>
<!--usage-->
#RenderSection("usage", required: false)
<!--other-->
#RenderSection("other", required: false)
<!--script-->
#RenderSection("script", required: false)
<head>
<body>
</body>
</html>

On your _Layout.cshtml page (Or any other master page) Use following code on inside of <head></head> tag.
#if (IsSectionDefined("SpecialOther"))
{
#RenderSection("SpecialOther")
}
On the page that you want special css,script or any other item, specify their refernces. e.g.,
#section SpecialOther{
<link href="~/css/responsive-tables.css" rel="stylesheet" />
<script src="~/js/datatables/extras/ZeroClipboard.js"></script>
}

Related

How can I render section in a children Partial view?

The runtime&SDK I am using is the newest version .net 6
Here are three Partial views in _Layout.cshtml of my project: header.cshtml/aside.cshtml/footer.cshtml .
Why I speared them to three parts for there are so many codes for them that I have to speare for coding convenient.
Now I need to add a section to the header.cshtml. Here is my code:
<header>
///some other codes
#RenderSection("ProductNav", required: false)
</header>
No matter there is a section "ProductNav", after the program ran, the page will all be blank without any error.
I found that it seems I can not use the RenderSection in a children Partial view.
It seems there is another way by using the Html.Partial to achieve this.
However, it needs to convert the views that I want to add to string. That's so troublesome.
Is there an easy way can achieve this? Thank you.
You want to show navbar on partial pages, You use partial view to achieve this function, But user can't add css style in partial view directly.
My idea is you can create a External CSS file in wwwroot and use it in page whitch needs to load partial view.
I write a demo to demonstrate the feasibility of this idea.
Views/Shared/_header.cshtml
<h2>This is head Partial View H2</h2>
<p>This is head Partial View P</p>
wwwroot/css/header.css
h2 {
color: blue;
}
p {
color: red;
}
views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - EmptyNEt5MVc</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
//add the css file in here
#await RenderSectionAsync("Css", required: false)
</head>
//.........
View
#{
ViewData["Title"] = "Privacy Policy";
}
//use partial view
<partial name="_header" />
<h1>#ViewData["Title"]</h1>
<p1>Use this page to detail your site's privacy policy.</p1>
//reference css file
#section Css{
<link rel="stylesheet" href="~/css/header.css" />
}
Then you can see the `header partial view' load the css file successfully
=============================================
In fact, View Component is more suitable for navigation bar than Partial View, There is a document about View Component.

Component not displaying on web

I'm adding a new web page to my app using polymer2. I've already done similar adds before but this one really does not show on the page even tho i have the imports and the components ready...
I'm starting to have some headaches watching my code trying to find what is wrong so maybe some of you will find the error instantly.
As i said before i've already implemented other pages on the app using the
Maybe the problem comes from the "lazy import" of my new component but it worked fine for the other previously added components.
i tried to look for misspelled DOM or components but everything looks fine
This is the menu from which i go to the other pages
<!-- i import the components like that -->
<link rel="lazy-import" href="c2m-connexion.html">
<link rel="lazy-import" href="c2m-newPage.html">
<app-drawer-layout id="drawerLayout" force-narrow>
<app-drawer id="drawer" slot="drawer" swipe-open="[[narrow]]">
<app-toolbar>Menu</app-toolbar>
<iron-selector selected="[[page]]" attr-for-selected="name" class="drawer-list" role="navigation">
<div id="anonyme">
<a name="connexion" href="[[rootPath]]connexion">Connexion</a>
<a name="newPage" href="[[rootPath]]newPage">New Page !!</a>
</div>
<!--[... Some other pages in the menu ...]-->
<div id="top ">
<iron-pages selected="[[page]]" attr-for-selected="name" fallback-selection="view404 " role="main ">
<c2m-connexion name="connexion"></c2m-connexion>
<c2m-newPage name="newPage" subroute="{{subroute}}"></c2m-newPage>
<!-- other pages implemented the same way-->
</iron-pages>
</div>
i use this script cause all my files have a normalised name :
// Load page import on demand. Show 404 page if fails
let resolvedPageUrl = this.resolveUrl('c2m-' + page + '.html');
Polymer.importHref(
resolvedPageUrl,
null,
this._showPage404.bind(this),
true);
}
Now the component itself (c2m-newPage) :
<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/paper-input/paper-input.html">
<link rel="import" href="../bower_components/paper-button/paper-button.html">
<link rel="import" href="../bower_components/paper-checkbox/paper-checkbox.html">
<link rel="import" href="../bower_components/paper-card/paper-card.html">
<link rel="import" href="../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../bower_components/neon-animation/web-animations.html">
<link rel="import" href="../bower_components/neon-animation/neon-animated-pages.html">
<link rel="import" href="../bower_components/neon-animation/neon-animations.html">
<link rel="import" href="./components/sweet-alert.html">
<link rel="import" href="shared-styles.html">
<link rel="import" href="./services/c2m-service.html">
<link rel="import" href="components/c2m-menu-newPage.html">
<dom-module id="c2m-newPage">
<!-- Defines the element's style and local DOM -->
<template>
<link rel="stylesheet" href="../style/main.css">
<link rel="stylesheet" href="../style/util.css">
<style is="custom-style" include="shared-styles">
:host {
display: flex;
padding: 9px;
}
paper-input#email-input {
width: 50%;
}
.card-content paper-dropdown-menu {
width: 100%;
}
</style>
<!-- I TRIED PUTTING SOME TEXT HERE ASWELL TO SEE IF THE COMPONENT WAS LOADING BUT NOTHING APPEARED -->
<c2m-menu-newPage></c2m-menu-newPage>
<!-- Services -->
<c2m-service id="service"></c2m-service>
</template>
<script>
class C2mNewPage extends Polymer.Element {
/**
* #inheritdoc
**/
connectedCallback() {
super.connectedCallback();
}
static get is() {
return 'c2m-newPage';
}
}
customElements.define(C2mNewPage.is, C2mNewPage);
</script>
</dom-module>
i expect the page to show something, at this point the text i tried to put didn't even show and i think if i put a some text it is supposed to appear on the page. So i don't know where it comes from.
Thanks for the answers !
Renaming the element to c2m-new-page probably solves your problem.
Polymer does not go well with capitals, since your element has the name 'c2m-newPage' it probably can't be found when used in the dom, since it searches for an element with lower letters or with the Capital replaced by a dash-lowercase.

PartialView getting data only for one View

Hey guys i'm using asp mvc4 for building a site,im having trouble in Views
First of all i have my _Layout View calling a partialView for header and my partial View is getting data from a model in to fill some data in the header,
It's working by the way just in the Main (index) view but moving to another views just call the Partial view without getting data from database.
Hope i explained Well :D
_layout View
#model MvcApplication1.Models.SchoolInfo
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>#Html.DisplayFor(model => model.SiteName)</title>
<!-- Bootstrap Core CSS -->
<link href="~/Content/Template/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="~/Content/Template/css/business-casual.css" rel="stylesheet">
<!-- Fonts -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Josefin+Slab:100,300,400,600,700,100italic,300italic,400italic,600italic,700italic" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<body>
<header>
<section id="login">
#Html.Partial("_LoginPartial")
#if (Request.IsAuthenticated)
{
#Html.Partial("_SiteHeaderPartial")
}
</section>
</header>
#RenderBody()
#if (Request.IsAuthenticated){
<footer>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<p>Copyright © Your Website footer</p>
</div>
</div>
</div>
</footer>
}
<!-- jQuery -->
<script src="~/Scripts/Template/js/jquery.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="~/Scripts/Template/js/bootstrap.min.js"></script>
<!-- Script to Activate the Carousel -->
<script>
$('.carousel').carousel({
interval: 5000 //changes the speed
})
</script>
_SiteHeaderPartial
#model MvcApplication1.Models.SchoolInfo
<div class="brand">#Html.DisplayFor(model => model.SchoolName)</div>
<div class="address-bar">Country | Address : #Html.DisplayFor(model => model.SchoolAddress) | 011 #Html.DisplayFor(model => model.SchoolPhone)
Index and About views are the same (empty).
If your not seeing the details in the About.cshtml view, its because you have not passed a SchoolInfo model to that view (or the model is not populated with the data). However a layout should not include a model declaration (unless its a base model from which all views that use that layout derive).
Remove #model MvcApplication1.Models.SchoolInfo from the layout and instead of #Html.Partial("_SiteHeaderPartial"), use
#Html.Action("SiteHeader", "yourControllerName")
where SiteHeader() is a a controller method that gets your data and returns a partial view, for example
[ChildOnlyAction]
public PartialViewResult SiteHeader()
{
SchoolInfo model = ... // populate your model
return PartialView("_SiteHeaderPartial", model);
}
Sife note: You also need to remove <title>#Html.DisplayFor(model => model.SiteName)</title> or replace it with (say) <title>#ViewBag.Title</title> and in each view, pass the value to the partial using #{ ViewVag.Title = someValue; }

where should i place the js script files in a mvc application so jquery works well?

the _layout.cshtml has code lines
#Scripts.Render("~/bundles/jquery")
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
by default they are placed inside the <body> tags by MVC. But when i leave them in this place some times jquery does not work. so i have decided to put those three lines in the <head> block in _layout.cshtml so the page will put styles and script files in the <head> as anyone would do with php or jsp. Good thing is when i put those files in <head> all my jquery started working again. But most MVC books says to place the scripts in the <body> block.
So where should i put them?
updated post:
here is my bundle file:
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
"~/Scripts/jquery-ui-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
}
here is the layout file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/modernizr")
#RenderSection("scripts", required: false)
</body>
</html>
Here is the view:
#{
ViewBag.Title = "TestPage";
}
<h2>TestPage</h2>
<input type="submit" name="name" value="Click me" id="btn"/>
<div id="d1"></div>
<script type="text/javascript">
$('#btn').click(function(){
alert('clicked');
});
</script>
here is teh video to show that click does not work
In your layout file, the script tag to load jQuery library is included at the end of the page. But there is another section called scripts below that. So in your individual pages ( Ex : Index,View etc..) You should be putting your javascript inside the section scripts
<body>
#RenderBody()
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
And in your views (Ex : Index view)
#section scripts{
<script src="~/Scripts/SomePageSpecificFile.js"></script>
<script>
$(function(){
// Your other js code goes here
});
</script>
}
So when razor render the page it will be
<body>
<script src="/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/SomePageSpecificFile.js"></script>
<script>
$(function(){
// Your other js code goes here
});
</script>
</body>
As long as you execute your page specific javascript which uses jQuery inside the scripts section ,you should be fine.

Modal dialog. - Confusing

I am trying to open a simple modal dialog and I have been struggling to do this. Can
any one please help? This is the HTML code(please remove pre). This simply doesnot work.
Can any one please tell **strong text**me why? I have not been getting the kind of output that I really
need.
Any one help me.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/magnific-popup.css" rel="stylesheet" />
<script src="js/jquery.magnific-popup.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
</head>
<body>
<a class="popup-modal" href="#test-modal">Open modal</a>
<div id="test-modal" class="white-popup-block mfp-hide">
<h1>Modal dialog</h1>
<p>You won't be able to dismiss this by usual means (escape or
click button), but you can close it programatically based on
user choices or actions.</p>
<p><a class="popup-modal-dismiss" href="#">Dismiss</a></p>
</div>
<script>
$(function () {
$('.popup-modal').magnificPopup({
type: 'inline',
preloader: false,
focus: '#username',
modal: true
});
$(document).on('click', '.popup-modal-dismiss', function (e) {
e.preventDefault();
$.magnificPopup.close();
});
});
</script>
</body>
</html>
Load jquery before the magnific-popup plugin, it relies on jquery (I've never used it but I'm assuming so seeeing as it is pre-appended withfixed 'jquery')
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link href="css/magnific-popup.css" rel="stylesheet" />
<!-- Jquery loaded first here... -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
<!-- Plugins after... -->
<script src="js/jquery.magnific-popup.js"></script>
</head>
<body>