Rather than use Stimulus targets to fetch data, I'd like to use Stimulus values in my controller but I can't find the way to retrieve it. Any idea how I could write it? Thanks.
This works:
HTML:
<div data-controller="admin-invoice-form">
<div data-target="admin-invoice-form.amountDiscountedTotal" value="100"><div>
<div>
STIMULUS:
static targets = ["amountDiscountedTotal"];
connect() {
console.log(this.amountDiscountedTotalTarget)
--> 100
}
This doesn't work:
HTML:
<div data-controller="admin-invoice-form">
<div data-admin-invoice-form-amount-discounted-total-value="100"><div>
<div>
STIMULUS:
static values = { amountDiscountedTotal: Number }
connect() {
console.log(this.amountDiscountedTotalValue);
--> undefined
console.log(this.data.get("amountDiscountedTotalValue"));
--> null
}
Related
I want to change the machine name based on the IMEI number, getting an error while writing if condition inside the div.
<div class="pull-right">
<small>(Imei : #item.DeviceImei)</small>
</div>
<div class="pull-right">
#if (item.DeviceImei==="868997035786332")
{
<small>(Machine : Power Complex)</small>
}
else
{
<small>(Machine:NA)</small>
}
</div>
it's because of your if. When you use an HTML tag, the Razor view engine will be off and you should use # for your next C# code, in this situation, you should use this:
<div class="pull-right">
<small>(Imei : #item.DeviceImei)</small>
</div>
<div class="pull-right">
#if (item.DeviceImei==="868997035786332")
{
<small>(Machine : Power Complex)</small>
}
#else
{
<small>(Machine:NA)</small>
}
</div>
I am building a small DNN MVC module whereby I need a user to upload file which will be processed server side.
When the form is posted back, the view model is posted back fine, but the file never is. Request.Files is always 0.
I even simplified it so all I had on the module was a simple file input and submit button but that failed as well.
I would hate to have to revert back to .ascx controls to get this to work.
I am testing this as an unregistered user, therefore there is no authentication checking in the controller.
See code below:
View
#inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<NM.Modules.FlexEventsCreate.Models.FlexEventViewModel>
#using DotNetNuke.Web.Mvc.Helpers
<input type="file" id="fileUp"/>
<input type="submit" id="btnSubmit" />
Controller
[DnnHandleError]
public class ItemController : DnnController
{
[HttpPost]
public ActionResult ShowForm(FlexEventViewModel flexEvent)
{
if (ModelState.IsValid)
{
var file = Request.Files;
if (file.Count != 0)
{
//do something
}
//return RedirectToDefaultRoute();
}
return View(flexEvent);
}
}
The rendered DNN HTML looks like this (I have simplified it)
<form method="post" action="/Test" id="Form" enctype="multipart/form-data">
<!-- Begin Content areas -->
<div>
<div class="row">
<div class="medium-9 columns">
<div id="dnn_LeftPane">
<div class="DnnModule DnnModule-DnnModule-747">
<a name="747"></a>
<div class="DnnF_Title_h1 SpacingBottom">
<h1><span id="dnn_ctr747_dnnTITLE_titleLabel" class="TitleH1"></span>
</h1>
<div id="dnn_ctr747_ContentPane">
<!-- Start_Module_747 -->
<div id="dnn_ctr747_ModuleContent">
<div id="dnn_ctr747_ShowForm_Prog" class="RadAjax RadAjax_Default" style="display:none;">
<div class="raDiv">
</div>
<div class="raColor raTransp">
</div>
</div>
<div class="RadAjaxPanel" id="dnn_ctr747_dnn_ctr747_ShowForm_UPPanel">
<div id="dnn_ctr747_ShowForm_UP">
<!-- 2013.2.717.40 -->
<div id="mvcContainer-747">
<input type="file" id="fileUp">
<input type="submit" id="btnSubmit">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
I did do an upload in an MVC module using the dropzone jquery component - which may help you. See my sample Restaurant Menu project on github.
First, include the dropzone script and css:
#using DotNetNuke.Web.Client.ClientResourceManagement
#{
ClientResourceManager.RegisterStyleSheet(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/css/dropzone.css");
ClientResourceManager.RegisterScript(Dnn.DnnPage, "~/DesktopModules/MVC/DotNetNuclear/RestaurantMenu/Resources/dropzone/js/dropzone.min.js", 100);
}
Then place a container div for the upload component:
<div id="dZUpload" class="uploadform dropzone no-margin dz-clickable">
<div class="dz-default dz-message"></div>
</div>
Initialize the component and tell it what type and how many files can be uploaded:
$("#dZUpload").dropzone({
acceptedFiles: "image/jpeg,image/png,image/gif",
url: '#Url.Action("Upload", "Menu")',
maxFiles: 1, // Number of files at a time
maxFilesize: 1, //in MB
addRemoveLinks: true,
maxfilesexceeded: function (file) {
alert('You have uploaded more than 1 Image. Only the first file will be uploaded!');
},
success: function (response) {
}
});
Change the acceptedFiles to the mimetypes you are restricting ("application/pdf", etc). Change the maxFiles to limit how many files they can upload at a time.
Write an MVC controller action to respond to the Dropzone file upload url. You can see it expects an action method "Upload" on the controller "Menu" (MenuController.Upload):
public JsonResult Upload()
{
string imageUrl = string.Empty;
string imgPath = Server.MapPath("~/Portals/0/Restaurant/");
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
foreach (string s in Request.Files)
{
var file = Request.Files[s];
if (file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(imgPath, fileName);
file.SaveAs(path);
imageUrl = string.Format("/Portals/0/Restaurant/{0}", fileName);
}
}
return Json(new { img = imageUrl, thumb = imageUrl });
}
A short background:
This example is a slightly more complicated version of my Angular Dart: Data binding doesn't work when manipulating the controller from the outside question that has been answered correctly. I only added a toggleable "show resolved comments" link to this version. Even though I initialized every variable to non-null values the problem still happens.
Full description of the actual problem:
I have two controllers nested into each other. The outer controller shows/hides the inner controller by using an ng-switch directive.
The outer controller also contains a checkbox. If this checkbox gets checked then the inner controller is made visible (via the above ng-switch directive). This checkbox works as intended.
There's also an "open" link outside the controllers. Its onclick handler calls into the outer controller and is supposed to check the checkbox via the model. The problem is that even though the model gets changed, the view doesn't get updated, unless I explicitly call scope.apply(), which I shouldn't. Even if I remove the comment before scope.apply() in my code then data binding doesn't work within InnerController.
This pattern has worked flawlessly in AngularJS but apparently doesn't in AngularDart.
I insist to this pattern or something similar because I'm in the process of integrating AngularDart into a legacy application that doesn't use data binding so I have to trigger model changes from outside the models.
Thanks in advance!
<html ng-app>
<head>
<title>Angular.dart nested controllers</title>
</head>
<body>
open
<div outer-controller ng-switch="outerCtrl.showInnerController">
<input type="checkbox" ng-model="outerCtrl.showInnerController">
<div inner-controller ng-switch-when="true">
Your name: <input ng-model="innerCtrl.yourName">
<br>
Hello {{innerCtrl.yourName}}!
<div ng-switch="innerCtrl.showResolvedComments" style="text-decoration:underline; color:blue; cursor:pointer">
<div ng-switch-when="true" ng-click="innerCtrl.showResolvedComments = false">Hide resolved comments</div>
<div ng-switch-when="false" ng-click="innerCtrl.showResolvedComments = true">Show resolved comments</div>
</div>
</div>
<div inner-controller ng-switch-when="false">
other controller
</div>
</div>
<script type="application/dart">
import "dart:html";
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
OuterController outerController;
#Controller(selector:'[outer-controller]', publishAs:'outerCtrl')
class OuterController {
bool showInnerController = false;
Scope scope;
OuterController(this.scope) {
outerController = this;
}
void showOuterController() {
showInnerController = true;
//scope.apply();
}
}
#Controller(selector:'[inner-controller]', publishAs:'innerCtrl')
class InnerController {
String yourName = 'defaultName';
bool showResolvedComments = true;
}
class MyAppModule extends Module {
MyAppModule() {
type(InnerController);
type(OuterController);
}
}
main() {
applicationFactory().addModule(new MyAppModule()).run();
querySelector('#open').onClick.listen((Event event) {
outerController.showOuterController();
});
}
</script>
</body>
</html>
After some experimentation, it's look like angular listen specified event to activate ng-model, and it doesn't look every variable change, i think because it's complicated to watch every change in variable without impact performance.
You can change your approach by simulate a user click on the check box
like:
CheckboxInputElement checkBox = querySelector("input");
if (checkBox.checked == false) {
checkBox.click();
}
It's maybe not the cleaner way to do this, but it works
Here the full code with the patch
<html ng-app>
<head>
<title>Angular.dart nested controllers</title>
</head>
<body>
open
<div outer-controller ng-switch="outerCtrl.showInnerController">
<input type="checkbox" ng-model="outerCtrl.showInnerController">
<div inner-controller ng-switch-when="true">
Your name: <input ng-model="innerCtrl.yourName">
<br>
Hello {{innerCtrl.yourName}}!
<div ng-switch="innerCtrl.showResolvedComments" style="text-decoration:underline; color:blue; cursor:pointer">
<div ng-switch-when="true" ng-click="innerCtrl.showResolvedComments = false">Hide resolved comments</div>
<div ng-switch-when="false" ng-click="innerCtrl.showResolvedComments = true">Show resolved comments</div>
</div>
</div>
<div inner-controller ng-switch-when="false">
other controller
</div>
</div>
<script type="application/dart">
import "dart:html";
import 'package:angular/angular.dart';
import 'package:angular/application_factory.dart';
OuterController outerController;
#Controller(selector:'[outer-controller]', publishAs:'outerCtrl')
class OuterController {
bool showInnerController = false;
Scope scope;
OuterController(this.scope) {
outerController = this;
}
void showOuterController() {
showInnerController = true;
print("showOuterController");
//scope.apply();
}
}
#Controller(selector:'[inner-controller]', publishAs:'innerCtrl')
class InnerController {
String yourName = 'defaultName';
bool showResolvedComments = true;
}
class MyAppModule extends Module {
MyAppModule() {
type(InnerController);
type(OuterController);
}
}
main() {
applicationFactory().addModule(new MyAppModule()).run();
querySelector('#open').onClick.listen((Event event) {
outerController.showOuterController();
// Added Code
CheckboxInputElement checkBox = querySelector("input");
if (checkBox.checked == false) {
checkBox.click();
}
// End added code
});
}
</script>
</body>
</html>
I've been trying to use backbonejs and jqm together.
I can render the main page alright. The page has a list that the user can tap on. The item selected should show a detail page with info on the list item selected. The detail page is a backbone view with a template that's rendered in the item's view object.
The detail's view .render() produces the html ok and I set the html of the div tag of the main page to the rendered item's detail markup. It looks like this:
podClicked: function (event) {
console.log("PodListItemView: got click from:" + event.target.innerHTML + " id:" + (this.model.get("id") ? this.model.get("id") : "no id assigned") + "\n\t CID:" + this.model.cid);
var detailView = new PodDetailView({ model: this.model });
detailView.render();
},
The detail view's render looks like this:
render: function () {
this.$el.html(this.template({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
var appPageHtml = $(app.el).html($(this.el));
$.mobile.changePage(""); // <-- vague stab in the dark to try to get JQM to do something. I've also tried $.mobile.changePage(appPageHtml).
console.log("PodDetailView: render");
return this;
}
I can see that the detail's view has been rendered on the page by checking Chrome's dev tools html editor but it's not displaying on the page. All I see is a blank page.
I've tried $.mobile.changePage() but, without an URL it throws an error.
How do I get JQM to apply it's class tags to the rendered html?
the HTML and templates look like this:
<!-- Main Page -->
<div id="lessa-app" class="meditator-image" data-role="page"></div>
<!-- The rest are templates processed through underscore -->
<script id="app-main-template" type="text/template">
<div data-role="header">
<h1>#ViewBag.Title</h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview" >
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="newPod" class="ez-icon-plus"></div>
</div>
</script>
<script id="poditem-template" type="text/template">
<span class="pod-listitem"><%= isAbout_Name %></span> <span class='pod-listitem ui-li-aside'><%= happenedOn %></span> <span class='pod-listitem ui-li-count'>5</span>
</script>
<script id="page-pod-detail-template" type="text/template">
<div data-role="header">
<h1>Pod Details</h1>
</div>
<div data-role="content">
<div id='podDetailForm'>
<fieldset data-role="fieldcontain">
<legend>PodDto</legend>
<label for="happenedOn">This was on:</label>
<input type="date" name="name" id="happenedOn" value="<%= happenedOn %>" />
</fieldset>
</div>
<button id="backToList" data-inline="false">Back to list</button>
</div>
<div data-role='footer'></div>
</script>
Thanks in advance for any advice... is this even doable?
I've finally found a way to do this. My original code has several impediments to the success of this process.
The first thing to do is to intercept jquerymobile's (v.1.2.0) changePage event like this:
(I've adapted the outline from jqm's docs and left in the helpful comments: see http://jquerymobile.com/demos/1.2.0/docs/pages/page-dynamic.html
)
$(document).bind("pagebeforechange", function (e, data) {
// We only want to handle changePage() calls where the caller is
// asking us to load a page by URL.
if (typeof data.toPage === "string") {
// We are being asked to load a page by URL, but we only
// want to handle URLs that request the data for a specific
// category.
var u = $.mobile.path.parseUrl(data.toPage),
re = /^#/;
// don't intercept urls to the main page allow them to be managed by JQM
if (u.hash != "#lessa-app" && u.hash.search(re) !== -1) {
// We're being asked to display the items for a specific category.
// Call our internal method that builds the content for the category
// on the fly based on our in-memory category data structure.
showItemDetail(u, data.options); // <--- handle backbone view.render calls in this function
// Make sure to tell changePage() we've handled this call so it doesn't
// have to do anything.
e.preventDefault();
}
}
});
The changePage() call is made in the item's list backbone view events declaration which passes to the podClicked method as follows:
var PodListItemView = Backbone.View.extend({
tagName: 'li', // name of (orphan) root tag in this.el
attributes: { 'class': 'pod-listitem' },
// Caches the templates for the view
listTemplate: _.template($('#poditem-template').html()),
events: {
"click .pod-listitem": "podClicked"
},
initialize: function () {
this.model.bind('change', this.render, this);
this.model.bind('destroy', this.remove, this);
},
render: function () {
this.$el.html(this.listTemplate({ podId: this.model.get("podId"), isAbout_Name: this.model.get("isAbout_Name"), happenedOn: this.model.get("happenedOn") }));
return this;
},
podClicked: function (event) {
$.mobile.changePage("#pod-detail-page?CID='" + this.model.cid + "'");
},
clear: function () {
this.model.clear();
}
});
In the 'showItemDetail' function the query portion of the url is parsed for the CID of the item's backbone model. Again I've adapted the code provided in the jquerymobile.com's link shown above.
Qestion: I have still figuring out whether it's better to have the code in showItemDetail() be inside the view's render() method. Having a defined function seems to detract from backbone's architecture model. On the other hand, having the render() function know about calling JQM changePage seems to violate the principle of 'separation of concerns'. Can anyone provide some insight and guidance?
// the passed url looks like #pod-detail-page?CID='c2'
function showItemDetail(urlObj, options) {
// Get the object that represents the item selected from the url
var pageSelector = urlObj.hash.replace(/\?.*$/, "");
var podCid = urlObj.hash.replace(/^.*\?CID=/, "").replace(/'/g, "");
var $page = $(pageSelector),
// Get the header for the page.
$header = $page.children(":jqmData(role=header)"),
// Get the content area element for the page.
$content = $page.children(":jqmData(role=content)");
// The markup we are going to inject into the content area of the page.
// retrieve the selected pod from the podList by Cid
var selectedPod = podList.getByCid(podCid);
// Find the h1 element in our header and inject the name of the item into it
var headerText = selectedPod.get("isAbout_Name");
$header.html("h1").html(headerText);
// Inject the item info into the content element
var view = new PodDetailView({ model: selectedPod });
var viewElHtml = view.render().$el.html();
$content.html(viewElHtml);
$page.page();
// Enhance the listview we just injected.
var fieldContain = $content.find(":jqmData(role=listview)");
fieldContain.listview();
// We don't want the data-url of the page we just modified
// to be the url that shows up in the browser's location field,
// so set the dataUrl option to the URL for the category
// we just loaded.
options.dataUrl = urlObj.href;
// Now call changePage() and tell it to switch to
// the page we just modified.
$.mobile.changePage($page, options);
}
So the above provides the event plumbing.
The other problem I had was that the page was not set up correctly. It's better to put the page framework in the main html and not put it in an underscore template to be rendered at a later time. I presume that avoids issues where the html is not present when jqm takes over.
<!-- Main Page -->
<div id="lessa-app" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<!-- /header -->
<div id="main-content" data-role="content">
<div id="pod-list" data-theme="a">
<ul data-role="listview">
</ul>
</div>
</div>
<div id="main-footer" data-role='footer'>
<div id="main-newPod" class="ez-icon-plus"></div>
</div>
</div>
<!-- detail page -->
<div id="pod-detail-page" data-role="page">
<div data-role="header">
<h1></h1>
</div>
<div id="detail-content" data-role="content">
<div id="pod-detail" data-theme="a">
</div>
</div>
<div id="detail-footer" data-role='footer'>
back
</div>
</div>
I'm new to ASP.NET MVC SPA and Knockout.js os maybe it's a simple mistake I made...
Situation: I have two partialviews in my website and I want that every partialview has his own Knockout ViewModel so I won't get a huge ViewModel.
My current ViewModel:
/// <reference path="../_references.js" />
function MobileDeliveriesViewModel() {
var self = this;
// Data
self.currentDelivery = ko.observable();
self.nav = new NavHistory({
params: { view: 'deliveries', deliveryId: null }
});
// Test
self.foo = "FooBar"
self.bar = "BarFoo"
self.nav.initialize({ linkToUrl: true });
// Navigate Operations
self.showDeliveries = function () { self.nav.navigate({ view: 'deliveries' }) }
self.showCustomers = function () { self.nav.navigate({ view: 'customers' }) }
}
function BarFooViewModel() {
var self = this
//MobileDeliveriesViewModel.call(self)
self.bar2 = "BarFooTwo"
}
ko.applyBindings(new MobileDeliveriesViewModel());
ko.applyBindings(new MobileDeliveriesViewModel(), $('#BarFoo')[0]);
ko.applyBindings(new BarFooViewModel(), document.getElementById('BarFoo'));
My Index.cshtml:
<div data-bind="if: nav.params().view == 'deliveries'">
#Html.Partial("_DeliveriesList")
</div>
<div class="BarFoo" data-bind="if: nav.params().view == 'customers'">
#Html.Partial("_CustomersList")
</div>
<script src="~/Scripts/App/DeliveriesViewModel.js" type="text/javascript"></script>
My CustomerPartialView:
<div id="BarFoo" class="content">
<p data-bind="text: bar"></p>
<p data-bind="text: bar2"></p>
<button data-bind="click: showDeliveries, css: { active: nav.params().view == 'deliveries' }">Deliveries</button>
</div>
My DeliveriesPartialView:
<div class="content">
<p data-bind="text: foo"></p>
<button data-bind="click: showCustomers, css: { active: nav.params().view == 'customers' }">Customers</button>
</div>
If I run this, it won't recognize the bar2 propertie in my BarFooViewModel...
I have tried 2 different applyBindings at the end of my ViewModel.
Anybody got an idea or is their a better way/pattern to do this?
are there JS errors on page?
nav.params().view
but params: { view: 'deliveries', deliveryId: null } - it's not function.
and if you want use a few view models on single page - check this http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+KnockMeOut+%28Knock+Me+Out%29 acticle. you have to use "stopBinding"
It looks like you are applying multiple data bindings to the same sections.
ko.applyBindings(new MobileDeliveriesViewModel();
This will bind to all elements one the page.
ko.applyBindings(new MobileDeliveriesViewModel(), $('#BarFoo')[0]);
this will try to bind to all elements inside the div
ko.applyBindings(new BarFooViewModel(), document.getElementById('BarFoo'));
This will also try to bind to all elements inside the div.
To keep things simple, you should try to bind a single view model to a single html section. I've found that trying to bind two view models in the same html section has been hard to get work correctly and trouble shoot.
Jack128's answer also makes some good points.