Include Local javascript file with global dependency for only a view - asp.net-mvc-4

I have a view like this
#model IEnumerable<DuckingOctoBear.Models.PostViewModel>
<p>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Create New", "Create")
}
</p>
<div class="">
#foreach (DuckingOctoBear.Models.PostViewModel item in Model)
{
<a href="/Posts/Details/#item.Post.Id" class="post-element">
<h4>#Html.DisplayFor(modelItem => item.Post.Title)</h4>
<h6>
Inserted by #item.User.UserName at #item.Post.Date.ToString("dd MMMM yyyy hh:ss")
</h6>
<article>
#Html.Raw(item.Post.Text)
</article>
<span>
#if (User.IsInRole("Administrator") || User.IsInRole("Editor"))
{
#Html.ActionLink("Edit", "Edit", new { id = item.Post.Id })
<span>|</span>
}
#Html.ActionLink("Details", "Details", new { id = item.Post.Id })
<span>|</span>
#if (User.IsInRole("Administrator"))
{
#Html.ActionLink("Delete", "Delete", new { id = item.Post.Id })
<span>|</span>
}
</span>
</a>
}
</div>
...where I would like include a Javascript file which have strong dependencies to other Javascript files already included in the _Layout.cshtml
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
How can I include that local file without register it in a bundle, and so for all views?

Ok epic fail
for this _Layout.cshtml
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
I could add just a new section
#RenderSection("LocallyScriptLibrary", required: false)
then in the target view doing just:
#section LocalScriptLibrary{
<script src="~/Scripts/LocalLibrary.js"></script>
}

Related

Returning html ID via path of Views of MVC controller

I am using wizard in my page and server side validation using razor view.
output page
Index.cshtml
For validation in #step-3/#step-2 wizard i want my page goes to id->step-3 but it goes to #step-1 or at the start of wizard page
I have to return the id of html page in returning views of controller.controller.cshtml
You can try to use Tempdata and js,here is a demo:
action:
[HttpPost]
public IActionResult Index(Contact contData)
{
TempData["id"] = "step-3";
return View();
}
View:
<div class="tab-content">
<div id="step-1" class="tab-pane fade">
<h3>Step 1</h3>
<p>Some content in step 1.</p>
</div>
<div id="step-2" class="tab-pane fade">
<h3>Step 2</h3>
<p>Some content in step 2.</p>
</div>
<div id="step-3" class="tab-pane fade">
<h3>Step 3</h3>
<p>Some content in step 3.</p>
</div>
</div>
<form method="post">
<button>submit</button>
</form>
#section Scripts{
<script>
$(function () {
var s = "#TempData["id"]";
var indexValue=0;
$(".tab-pane").each(function (index) {
if ($(this).attr("id") == s) {
$(this).addClass("in active");
indexValue=index;
} else {
$(this).removeClass("in active");
}
})
$(".myClass").each(function (index) {
if (indexValue==index) {
$(this).addClass("active");
indexValue=index;
} else {
$(this).removeClass("active");
}
})
})
</script>
}
result:

How to pass IEnumerable model to _Layout.cshtml

I need to pass a model to _Layout page for dynamic content editing.
Here is my _Layout
#model IEnumerable<Test.Models.Article>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
...
Later in _Layout I need to use this:
#Html.Raw(Model.Where(x => x.Id == 1).Single().Content) - this works fine
<a asp-controller="Articles" asp-action="Edit" asp-route-id="1">Edit</a> - error after clicking the edit button
This concept is working fine on all pages like Index, About etc. but not on _Layout.cshtml.
I get this error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Test.Models.Article', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.IEnumerable`1[Test.Models.Article]'.
What shoud I do?
Edit:
Here is my HomeController:
public class HomeController : Controller
{
public ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
return View(await _context.Article.ToListAsync());
}
public async Task<IActionResult> About()
{
return View(await _context.Article.ToListAsync());
}
}
Here is my ArticleController:
public class ArticlesController : Controller
{
public ApplicationDbContext _context;
public ArticlesController(ApplicationDbContext context)
{
_context = context;
}
// GET: Articles
public async Task<IActionResult> Index()
{
return View(await _context.Article.ToListAsync());
}
// GET: Articles/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var article = await _context.Article.FindAsync(id);
if (article == null)
{
return NotFound();
}
return View(article);
}
// POST: Articles/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Content")] Article article)
{
if (id != article.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(article);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ArticleExists(article.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(article);
}
The whole _Layout:
#model IEnumerable<Test.Models.Article>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - PermanentTetovani</title>
<environment include="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/css/default.css" />
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.css" />
</environment>
<environment exclude="Development">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
<link rel="stylesheet" href="~/lib/font-awesome/css/font-awesome.min.css" />
</environment>
</head>
<body>
<partial name="_CookieConsentPartial" />
<!-- HEADER : begin -->
<header id="header" class="m-animated">
<div class="header-bg">
<div class="header-inner">
<!-- HEADER BRANDING : begin -->
<div class="header-branding">
<a asp-controller="Home" asp-action="Index"><img src="../images/logo.png" alt="Permanentní tetování" data-hires="../images/logo.2x.png" width="291"></a>
</div>
<!-- HEADER BRANDING : end -->
<!-- HEADER NAVIGATION : begin -->
<div class="header-navigation">
<!-- HEADER MENU : begin -->
<nav class="header-menu">
<button class="header-menu-toggle" type="button"><i class="fa fa-bars"></i>MENU</button>
<ul>
<li class="#((ViewBag.PageName == "Index") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Index">Úvodní stránka</a></span>
</li>
<li class="#((ViewBag.PageName == "About") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="About">O nás</a></span>
</li>
<li class="#((ViewBag.PageName == "Gallery") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Gallery">Galerie</a></span>
</li>
<li class="#((ViewBag.PageName == "Contact") ? "m-active" : "")">
<span><a asp-controller="Home" asp-action="Contact">Kontakt</a></span>
</li>
</ul>
</nav>
<!-- HEADER MENU : end -->
</div>
<!-- HEADER NAVIGATION : end -->
<!-- HEADER PANEL : begin -->
<div class="header-panel">
<button class="header-panel-toggle" type="button"><i class="fa"></i></button>
<!-- HEADER RESERVATION : begin -->
<div class="header-reservation">
<a asp-controller="Home" asp-action="Contact" class="c-button">Domluvit si schůzku</a>
</div>
<!-- HEADER RESERVATION : end -->
<!-- HEADER CONTACT : begin -->
<div class="header-contact">
<ul>
<!-- PHONE : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-phone"></i>
<strong>721 805 741</strong>
</div>
</li>
<!-- PHONE : end -->
<!-- EMAIL : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-envelope-o"></i>
777michaelahavlova<br>
##seznam.cz
</div>
</li>
<!-- EMAIL : end -->
<!-- ADDRESS : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-map-marker"></i>
<strong>PERMANENT TETOVÁNÍ</strong><br>
Jihočeská univerzita, Vančurova 2904<br>
Tábor 390 01
</div>
</li>
<!-- ADDRESS : end -->
<!-- HOURS : begin -->
<li>
<div class="item-inner">
<i class="ico fa fa-clock-o"></i>
<dl>
<dt>Po. - Pá.:</dt>
<dd>Dle dohody</dd>
<dt>So.:</dt>
<dd>Dle dohody</dd>
<dt>Ne.:</dt>
<dd>Zavřeno</dd>
</dl>
</div>
</li>
<!-- HOURS : end -->
</ul>
</div>
<!-- HEADER CONTACT : end -->
</div>
<!-- HEADER PANEL : end -->
</div>
</div>
</header>
<!-- HEADER : end -->
<!-- WRAPPER : begin -->
<div id="wrapper">
#RenderBody()
<!-- BOTTOM PANEL : begin -->
<div id="bottom-panel">
<div class="bottom-panel-inner">
<div class="container">
<div class="row">
<div class="col-md-6">
<!-- BOTTOM TEXT : begin -->
<div class="bottom-text various-content">
<h3>O našem studiu</h3>
<!--
<p><strong>Permanentní make-up</strong> provádím v Táboře v Jihočeské univerzitě, kde nabízím tyto služby: <strong>permanentní tetování obočí, rtů a očních linek</strong>.</p>
<p>Je potřeba se nejprve předem objednat!</p>
-->
#Html.Raw(Model.Where(x => x.Id == 1).Single().Content)
<a asp-controller="Articles" asp-action="Edit" asp-route-id="1">Edit</a>
</div>
<!-- BOTTOM TEXT : end -->
</div>
<div class="col-md-6">
<!-- BOTTOM SUBSCRIBE : begin -->
<div class="bottom-subscribe various-content">
<h3>Kontakt</h3>
<p>Využijte prosím náš kontaktní formulář.</p>
<a asp-controller="Home" asp-action="Contact" class="c-button">Kontaktujte nás</a>
</div>
<!-- BOTTOM SUBSCRIBE : end -->
</div>
</div>
</div>
</div>
</div>
<!-- BOTTOM PANEL : end -->
<!-- FOOTER : begin -->
<footer id="footer">
<div class="container">
<!-- FOOTER BOTTOM : begin -->
<div class="footer-bottom">
<div class="row">
<div class="col-md-6 col-md-push-6">
<!-- FOOTER MENU : begin -->
<nav class="footer-menu">
<ul>
<li><a asp-controller="Home" asp-action="Index">Úvodní stránka</a></li>
<li><a asp-controller="Home" asp-action="About">O nás</a></li>
<li><a asp-controller="Home" asp-action="Gallery">Galerie</a></li>
<li><a asp-controller="Home" asp-action="Register">Administrace</a></li>
</ul>
</nav>
<!-- FOOTER MENU : end -->
</div>
<div class="col-md-6 col-md-pull-6">
<!-- FOOTER TEXT : begin -->
<div class="footer-text">
<p>
©
<script type="text/javascript">
var today = new Date()
var year = today.getFullYear()
document.write(year)
</script>
PermanentTetovani.cz | Vytvořil ProgNet.cz
</p>
</div>
<!-- FOOTER TEXT : end -->
</div>
</div>
</div>
<!-- FOOTER BOTTOM : end -->
</div>
</footer>
<!-- FOOTER : end -->
</div>
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
#RenderSection("Scripts", required: false)
</body>
</html>
#Lukáš, I found the reason of your exception and will try my best to describe it.
From the process below, when reload edit view, it will load _layout.cshtml then render Edit.cshtml.You defined the #model IEnumerable<Test.Models.Article>
but return view(Ariticle).
What's the simplest solution?
open Views/Articles/Edit.cshtml add codes below
#{
Layout = null;
}
Screenshots of test:
WARNING
I have to remind you even though Edit works but others still have same problems.
_Layout.cshtml was added to each Views from _ViewStart.cshtml.
The layout specified can use a full path (for example, /Pages/Shared/_Layout.cshtml or /Views/Shared/_Layout.cshtml) or a partial name (example: _Layout). When a partial name is provided, the Razor view engine searches for the layout file using its standard discovery process. The folder where the handler method (or controller) exists is searched first, followed by the Shared folder. This discovery process is identical to the process used to discover partial views.
The details about Layout in ASP.NET Core.

Aurelia dialog is shown more than once

When opening a dialog, it is shown more than once
Tried to prevent double opening by checking if a dialog is already open
if (!this.dialogService.hasOpenDialog) {
return this.dialogService
.open({ viewModel: AssignTeam })
.whenClosed((response) => {
if (!response.wasCancelled) {
return this.protectionService.assignTeam(devices, response.output);
}
this.selectedDevices.splice(0);
});
}
Expected: One dialog should be shown. When the user clicks ok it should be gone
Actual: The dialog is opened more than once. When the user clicks ok, he is presented by the same dialog and has to cancel it
Here is the html when opening the dialog:
<body class="ux-dialog-open">
<ux-dialog-overlay style="z-index: 1000;" class="active"></ux-dialog-overlay>
<ux-dialog-container style="z-index: 1000;" class="active">
<div style="margin-top: 84.5px; margin-bottom: 84.5px;">
<div>
<div class="popup">
<div class="black-bg1">
<ai-dialog class="modalpopup-container padd35 dis-block">
<ai-dialog-header>
<!-- omitted -->
</ai-dialog-header>
<ai-dialog-body>
<!-- ommited-->
</ai-dialog-body>
<ai-dialog-footer class="text-center">
<!-- ommitted-->
</ai-dialog-footer>
</ai-dialog>
</div>
</div>
</div>
</div>
</ux-dialog-container>
<ux-dialog-overlay style="z-index: 1000;" class="active"></ux-dialog-overlay>
<ux-dialog-container style="z-index: 1000;" class="active">
<div style="margin-top: 84.5px; margin-bottom: 84.5px;">
<div>
<div class="popup">
<div class="black-bg1">
<ai-dialog class="modalpopup-container padd35 dis-block">
<ai-dialog-header>
<!-- omitted-->
</ai-dialog-header>
<ai-dialog-body>
<!-- omitted-->
</ai-dialog-body>
<ai-dialog-footer class="text-center">
<!-- omitted-->
</ai-dialog-footer>
</ai-dialog>
</div>
</div>
</div>
</div>
</ux-dialog-container>
<script id="__bs_script__">
//<![CDATA[
document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.26.3'><\/script>".replace("HOST",
location.hostname));
//]]>
</script>
<script async="" src="/browser-sync/browser-sync-client.js?v=2.26.3"></script>
<div aurelia-app="main" class="page_container">
<!-- omitted-->
</div>
<script src="scripts/vendor-bundle.js"></script>
<script>
requirejs.config({
skipDataMain: true
});
// Configure Bluebird Promises.
Promise.config({
longStackTraces: false,
warnings: false,
cancellation: true
});
require(['aurelia-bootstrapper']);
</script>
<div></div>
<div></div>
</body>
Also tried to investigate more, using this code:
if (!this.dialogService.hasActiveDialog) {
console.log(this.dialogService);
return this.dialogService
.open({ viewModel: AssignTeam })
.then((openDialogResult: DialogOpenResult) => {
console.log(openDialogResult);
return openDialogResult.closeResult;
});
DialogService debug
It seems like two controllers are allocated

HTML.BeginForm doesn't call the proper action

I have a this part in Edit.chtml looks like
#using (#Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<article class="SearchBoxCon clearfix">
#if (Model.Entity.Document == null)
{
using (Html.BeginForm("AudioUpload", "Noun", FormMethod.Post, new { enctype = "multipart/form-data", NounId = Model.Entity.Id }))
{
<article class="BtnCon">
<article class="BrowseBtn">
<input type="file" value="Browse" name="file">
</article>
<article class="BrowseUpload">
<input type="submit" id="AudioUpload" value="AudioUpload">
</article>
</article>
}
}
else
{
<article class="inputBTn">
<input type="submit" value="Play">
<input type="submit" value="Delete">
</article>
}
</article>
<article class="inputBTn">
<input type="submit" value="Save">
</article>
<!-- submit btn ends here -->
#Html.ActionLink("Back to List", "Index", "Noun/Index", null, new { #class = "BackList" })
</article>
}
after browsing and upload the file , and click the upload it fire the edit posting action instead of the uploadaudio which looks like
[HttpPost]
public ActionResult AudioUpload(HttpPostedFileBase file , int NounId )
{
[ActionName("Edit")] put attribute on your action method it will work
[HttpPost, ActionName("Edit")]
public ActionResult AudioUpload(HttpPostedFileBase file , int NounId )
{
make you code like this if your view name is Edit.cshtml
Try like this,
#if (Model.Entity.Document == null)
{
using (Html.BeginForm("AudioUpload", "Noun", FormMethod.Post, new { enctype = "multipart/form-data", NounId = Model.Entity.Id,Id="frmAudioUpload" }))
{<article class="BtnCon">
<article class="BrowseBtn">
<input type="file" value="Browse" name="file">
</article>
<article class="BrowseUpload">
<input type="button" id="AudioUpload" value="AudioUpload">
</article>
</article>
}}
Script
<script type="text/javascript">
$(function(){
$('#AudioUpload').click(function(){
$('#frmAudioUpload').submit();
});
});
</script>

What is the correct way to save a modified record (EMBER 1.0.0-PRE.4)

I have developed a small test application. Loading the person records
works as expected. I can modify firstName and lastName.
In the personedit template I have a action which triggers the save method of
the App.PersonController.
What is the best way to save the modified record (implementation of the save method) ?
JavaScript:
window.App = Ember.Application.create();
DS.RESTAdapter.configure("plurals",{"person" : "people"})
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter.create({namespace: 'restservice'})
});
var attr = DS.attr;
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthDay: attr('string')
});
App.Router.map(function(){
this.resource('people',function(){
this.resource('person',{path: 'people/:person_id'});
this.route('edit');
});
});
App.PersonRoute = Ember.Route.extend({
model: function(params){
console.log('PersonRoute: set Model ==> perform App.Person.find(params.person_id)')
var p = App.Person.find(params.person_id);
return p;
},
renderTemplate: function(){
this.render('person');
this.render('personedit',{outlet: 'personedit'});
}
});
App.PersonController = Ember.Controller.extend({
save: function(){
console.log('save: Person:',this.content);
}
});
App.PeopleEditRoute = Ember.Route.extend({
model: function(params){
console.log('EditpersonRoute: set Model ==> perform App.Person.find(params.person_id)')
var p = App.Person.find(params.person_id);
return p;
}
});
Templates:
<script type="text/x-handlebars" data-template-name="application">
<nav>
<div class="navbar">
<div class="navbar-inner">
<ul class="nav">
<li>{{#linkTo "people"}}Personen anzeigen{{/linkTo}}</li>
<li>{{#linkTo "page1"}}Page 1 anzeige{{/linkTo}}</li>
<li>{{#linkTo "page2"}}Page 2 anzeige{{/linkTo}}</li>
</ul>
</div>
</div>
</nav>
<div id="main-content">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="people">
<div id="people">
<H3>Personen Liste</H3>
<ul>
{{#each person in controller}}
<li>
{{#linkTo "person" person}} {{person.firstName}} {{person.lastName}} {{/linkTo}}
</li>
{{/each}}
</ul>
</div>
<div class="row-fluid">
<div class="span6">
{{outlet}}
</div>
<div class="span6">
{{outlet personedit}}
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="person">
<div id="person" class="inline">
<H3>Person View</H3>
<dl>
<dt>Vorname</dt>
<dd>{{content.firstName}}</dd>
<dt>Nachname</dt>
<dd>{{content.lastName}}</dd>
</dl>
</div>
</div>
</script>
<script type="text/x-handlebars" data-template-name="personedit">
<H3>EDITOR</H3>
<fieldset>
<legend>Person</legend>
<label>Vorname</label>
{{view Ember.TextField valueBinding="content.firstName"}}
<span class="help-block">Example block-level help text here.</span>
<label>Nachname</label>
{{view Ember.TextField valueBinding="content.lastName"}}
<button {{action "save" }} class="btn">Save</button>
</fieldset>
</script>
I have found the correct way of saving in another answer. The implementation of my save method needs only one additional line:
App.PersonController = Ember.Controller.extend({
save: function(){
console.log('save: Person:',this.content);
this.content.get('transaction').commit();
}