ASP_MVC5 - ANGULAR - Shared Variable with provider - asp.net

I'm about ASP net coupled with angularjs.
I have a main layout and 2 content pages
I want to spend my globals variables in page1 to page2.
I use a provider to pass the variable.
here's my problem: I just can not get a variable in my page2.
my layout page :
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - Mon application ASP.NET</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body ng-app="MainApp">
<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")
<script src="~/Scripts/angular.js"></script>
<script src="~/MyScripts/MainApp.js"></script>
<script src="~/MyScripts/Page1Ctrl.js"></script>
<script src="~/MyScripts/Page2Ctrl.js"></script>
<script src="~/MyScripts/GlobalParam.js"></script>
</body>
</html>
my page 1:
#{
ViewBag.Title = "¨Page1";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<div ng-controller="Page1Ctrl">
<p><a class="btn btn-default" ng-click="passVariable('5')">Pass variable (5) to Page2 with provider</a></p>
</div>
My page 2 :
#{
ViewBag.Title = "¨Page2";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<div ng-controller="Page2Ctrl">
<label>received value : {{reveiveValue}}</label>
</div>
my main APP :
var MainApp = angular.module('MainApp',
[
'Page1App',
'Page2App',
'GlobalParam'
]);
My pageCtrl1:
'use strict';
var Page1App = angular.module('Page1App', ['GlobalParam'])
Page1App.controller('Page1Ctrl', function ($scope, $window, Param) {
$scope.passVariable = function (val) {
$scope.shared = val;
$window.location.href = '/Home/Page2';
}
})
My pageCtrl2 :
'use strict';
var Page2App = angular.module('Page2App', ['GlobalParam'])
Page2App.controller('Page2Ctrl', function ($scope, Param) {
$scope.reveiveValue = Param.value;
})
My service :
angular.module('GlobalParam', [])
.provider('Param', [function () {
this.$get = ['$http', '$q',
function ($http, $q) {
return {
value:0
};
}];
}])
thank you for your help

Here you are doing a server side redirect:
$window.location.href = '/Home/Page2';
which obviously will perform a roundtrip to the server and a full page reload. This will kill any javascript/angular stuff you might have done. So if you want to pass some variable during a server side redirect you can use query string parameters:
$scope.passVariable = function (val) {
$window.location.href = '/Home/Page2?myVariable=' + encodeURIComponent(val);
}
and in your target view you can render this variable using the server side Razor template:
<label>received value : #Request["myVariable"]</label>
And if you wanted to retrieve the value of this server side variable on the client you may create some global variable in your template:
<script>
window.myVariable = #Html.Raw(Json.Encode(Request["myVariable"]));
</script>
And then use window.myVariable where needed in your scripts.
If on the other hand you want to have a SPA application then you should not be doing any server side redirects. You may consider in this case using angular ui router which allows you to pass variables during client side redirects (redirects that modify only the fragment portion of the url - #).

I did a little test.
why I'm always redirected to the server?
Main HTML :
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>MainApp</title>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/MyScripts/MainApp.js"></script>
<script src="~/MyScripts/Page1Ctrl.js"></script>
<script src="~/MyScripts/Page2Ctrl.js"></script>
<script src="~/MyScripts/GlobalParam.js"></script>
</head>
<body ng-app="MainApp">
<ul class="nav navbar-nav">
<li>Page1</li>
<li>Page2</li>
</ul>
<div>
<div ng-view></div>
</div>
</body>
</html>
MainApp.js
var MainApp = angular.module('MainApp', ["ngRoute"]);
MainApp.factory("ShareData", function () {
return { value: 0 }
});
//Defining Routing
MainApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
$routeProvider.when('/Page1',
{
templateUrl: 'Home/Page1',
controller: 'Page1Ctrl'
});
$routeProvider.when('/Page2',
{
templateUrl: 'Home/Page2',
controller: 'Page2Ctrl'
});
// $locationProvider.html5Mode(true);
//$locationProvider.html5Mode(true).hashPrefix('!')
}]);
Controlleur ASP :
public class HomeController : Controller {
public ActionResult MainApp() {
return View();
}
public ActionResult Page1() {
return View();
}
public ActionResult Page2() {
return View();
}
}

Related

Handlebars display AJAX JSON response

I am new to handlebars.js and I am trying to display a JSON response with this API https://yts.am/api/v2/list_movies.json
I try to use static and basic JSON data, it is working but when I try to load huge amount I get error
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<h1 id="title"></h1>
<hr>
<div id="result"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script id="text-template-yts" type="text/x-handlebars-template">
<h2>{{title}}</h2>
<h3>{{summary}}</h3>
<ul>
{{#each torrents}}
<li>{{quality}}</li>
{{/each}}
</ul>
</script>
<script>
function ajax_get(url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
try {
var data = JSON.parse(xmlhttp.responseText);
} catch (err) {
console.log(err.message + " in " + xmlhttp.responseText);
return;
}
callback(data);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
ajax_get('https://yts.am/api/v2/list_movies.json', function (data) {
document.getElementById("title").innerHTML = data["status_message"];
var source = document.getElementById('text-template-yts').innerHTML;
var template = Handlebars.compile(source);
var html = template(data.data.movies);
document.getElementById("result").innerHTML = html;
});
</script>
</body>
</html>
I was able to get the query success but in parsing is error
FIXED
I need to add the each of handlebars

How to get refresh token from Google Sign-In?

I created a prototype to ask the permission from User for accessing their Google Calendar by using ASP.NET WebForms.
Here is my code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="GoogleSignInDemo.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id" content="CLIENT_ID.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="Resources/jquery.js" ></script>
</head>
<body>
<div class="g-signin2" data-theme="dark" onclick="onSignInCalendar()"></div>
<script>
function onSignInCalendar() {
var auth2 = gapi.auth2.getAuthInstance();
var options = new gapi.auth2.SigninOptionsBuilder(
{ 'scope': 'email https://www.googleapis.com/auth/calendar' });
googleUser = auth2.currentUser.get();
googleUser.grant(options).then(
function (success) {
console.log(JSON.stringify({ message: "success", value: success }));
var accessToken = success.Zi.access_token;
var idToken = success.Zi.id_token;
},
function (fail) {
alert(JSON.stringify({ message: "fail", value: fail }));
});
}
</script>
</body>
</html>
It works fine. However, the response from google only contain access_token and id_token. I can't find refresh_token in there.
Any knows how to get it?

how to bind directive scope value to template in angularjs

I am trying to bind the id property value for a div using angularjs directive
I want a div container where id of the container will be passed as the parameter from the directive
<!DOCTYPE html>
<html lang="en" ng-app="directivesModule">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>
<script src="scripts/angular.js"></script>
<script>
(function() {
var zdMap = function() {
var template = '<div id="{{scope.mapId}}" > abd</div>'
function link(scope, elem, attrs) {
console.log("**********************"+scope.mapId)
}
return {
scope: {
mapId:'#'
},
link: link,
template: template
};
};
angular.module('directivesModule', [])
.directive('zdMap', zdMap);
}());
</script>
</body>
</html>
but when i see inspect the element in bowser i am getting empty id value
please say how to go about it i need to bind the value of directive parameter to the template
You should not use the scope in the template outside of link function.
(function() {
var zdMap = function() {
var template = '<div id="{{mapId}}" > abd</div>'
function link(scope, elem, attrs) {
console.log("**********************"+scope.mapId)
}
return {
scope: {
mapId:'#'
},
link: link,
template: template
};
};
angular.module('directivesModule', [])
.directive('zdMap', zdMap);
}());
<!DOCTYPE html>
<html lang="en" ng-app="directivesModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>
</body>
</html>
Please run the above snippet and check the id
Since you're using angular 1.5+ might I suggest using .component rather than .directive
(function() {
var zdMap = function() {
var template = '<div id="{{$ctrl.mapId}}" > abd</div>'
function controller() {console.log(this.mapId)}
return {
bindings: { // HERE !!
mapId:'#'
},
controller: controller
template: template
};
};
angular.module('componentModule', [])
.component('zdMap', zdMap); // here!!!!
}());
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="componentModule">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3>zendynamix Map Directive</h3>
<zd-map map-id="indexmap" ></zd-map>
</body>
</html>

TypeError: 'undefined' is not an object (evaluating 'text.replace') - when testing backbone view

I am trying to write the tests for a Backbone app which uses twig and symphony to render the underscore templates, using mocha, chai and sinon, with blanket for code-coverage and phantomjs for browser simulation. I have managed to load the template markup into test.html by doing the following in the body tag:
<!-- fixtures -->
<script>
$(function(){
$("#fixtures").load("fixtures/comment-fixture.html");
});
</script>
I have created a html fixture, or at least that is what I was aiming for, however I still get the following error when running my tests:
TypeError: 'undefined' is not an object (evaluating 'text.replace')
I understand that it refers to basically underscore evaluating _template(undefined), but I don't understand why it is doing that. Has anyone come across the a similar issue before or know why it is triggering this error?
This is my set-up:
Backbone view I want to test:
var CommentView = Backbone.View.extend({
//... is a list tag.
tagName: "li",
model: null,
// Cache the template function for a single item.
template: _.template($('#comment-template').html()),
// This is the timeout used to re-render the times
refreshTimer: null,
initialize: function(options) {
this.model = options.model;
this.listenTo(this.model, 'change', this.render);
this.listenTo(Backbone, 'stopCommentRefresh', this.stopRefreshTimer);
},
render: function() {
this.$el.html(this.template(this.model.renderAttributes()));
this.refreshTimer = setTimeout(_.bind(this.render, this), 60000);
return this;
},
// If you hit `enter`, we're through editing the item.
updateOnEnter: function(e) {
if (e.keyCode == 13) this.close();
},
stopRefreshTimer: function () {
clearTimeout(this.refreshTimer);
this.remove();
}
});
My fixture file for it :
<script type="text/template" id="comment-template">
<article class="comment">
<h4><%- user.username %></h4>
<p><%- comment %></p>
<time><%- time %></time>
</article>
</script>
My test file for it (so far nothing special):
describe("Comment View", function () {
before(function () {
// create test fixture
this.$fixture = $('<li id="comment-view-fixture"></li>');
});
beforeEach(function () {
// empty out and rebind the fixture for each run
this.$fixture.empty().appendTo($("#fixtures"));
// new default model and view for each test
this.view = new CommentView ({
el: this.$fixture,
model: new Comment({
comment: "Hello world!",
created: new Date(),
modified: new Date(),
user: {
username: "Mario"
}
})
});
});
afterEach(function () {
this.view.model.destroy();
});
after(function () {
$("#fixtures").empty();
});
});
And my test.html file:
<html>
<head>
<title>Backbone.js Tests</title>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="js/lib/mocha.css" />
</head>
<body>
<div id="blanket-main" class="hidden" style="display: none;"></div>
<div id="mocha"></div>
<!-- Utility libraries -->
<script src="js/lib/mocha.js"></script>
<script src="js/lib/chai.js"></script >
<script src="js/lib/sinon-chai.js"></script >
<script src="js/lib/sinon.js"></script >
<script src="js/lib/chai-datetime.js"></script>
<!-- JavaScript Coverage Libraries. -->
<script src="js/lib/blanket.js"></script>
<!-- jquery library -->
<script src="../../../../ApiBundle/Resources/public/js/thirdParty/jquery-1.11.js"></script>
<!-- fixtures -->
<script>
$(function(){
$("#fixtures").load("fixtures/comment-fixture.html");
});
</script>
<!-- JavaScript Core Libraries -->
<script src="../../../../ApiBundle/Resources/public/js/thirdParty/underscore.js"></script>
<script src="../../../../ApiBundle/Resources/public/js/thirdParty/jquery.dataTables.js"></script>
<script src="../../../../ApiBundle/Resources/public/js/thirdParty/backbone.js"></script>
<!-- Javascript Application Libraries - Views -->
<script src="../../../../ApiBundle/Resources/public/js/comment.js" data-cover></script>
<script>
var expect = chai.expect;
mocha.setup({
ui: "bdd",
globals: ['stats', 'failures', 'runner'], // Blanket leaks.
bail: false
});
// Set up Mocha with custom Blanket.js reporter.
mocha.reporter(function (_reporter) {
// Updated for Mocha 1.15.1 integration.
// See: https://github.com/alex-seville/blanket/pull/356
var blanketReporter = function (runner) {
// Listeners.
runner.on("start", function () { blanket.setupCoverage(); });
runner.on("suite", function () { blanket.onModuleStart(); });
runner.on("test", function () { blanket.onTestStart(); });
runner.on("test end", function (test) {
blanket.onTestDone(test.parent.tests.length,
test.state === 'passed');
});
runner.on("end", function () {
blanket.onTestsDone();
$("#blanket-main").removeClass("hidden").show("fast");
$("html, body").animate({ scrollTop: 0 });
});
_reporter.call(this, runner);
};
blanketReporter.prototype = _reporter.prototype;
return blanketReporter;
}(mocha._reporter));
blanket.beforeStartTestRunner({
callback: function () {
(window.mochaPhantomJS || mocha).run();
}
});
</script>
<script src="js/spec/views/view_CommentView.spec.js"></script>
<!-- Coverage style helpers -->
<style type="text/css">
#blanket-main {
margin-top: 65px;
margin-right: 20px;
margin-left: 20px;
border-radius: 5px;
border: 1px solid #666;
}
</style>
<!-- Test Fixtures. -->
<div id="fixtures" style="display: none; visibility: hidden;"></div>
</body>
</html>
It turns out its because $("#fixtures").load("fixtures/comment-fixture.html") is asynchronous and isn't actually loaded when I run the tests. By simply copying the contents of fixture.html into test.html body tag, the error stops happening!

How to implement manifest cache for mvc application

I am trying to implement manifest for one page. i don't have any idea how to implement the manifest, using below reference i implemented. but its not working.
http://www.codemag.com/Article/1112051.
My doubt: In local after implementing manifest even if visual studio not in debug mode, after refresh the page it should show the page right? here its not showing.
Please help how to implement manifest in mvc.
Here is the my code:
Home Controller:
public ActionResult Index()
{
Response.Cache.SetCacheability(
System.Web.HttpCacheability.NoCache);
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult Manifest()
{
Response.ContentType = "text/cache-manifest";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Cache.SetCacheability(
System.Web.HttpCacheability.NoCache);
return View();
}
Index.cshtml:
<html manifest="#Url.Action("Manifest", "Home")">
<head>
<title></title>
<link href="~/Content/kendo/2014.2.903/kendo.common.min.css" rel="stylesheet" />
<link href="~/Content/kendo/2014.2.903/kendo.default.min.css" rel="stylesheet" />
<link href="~/Content/kendo/2014.2.903/kendo.dataviz.min.css" rel="stylesheet" />
<link href="~/Content/kendo/2014.2.903/kendo.dataviz.default.min.css" rel="stylesheet" />
<script src="~/Scripts/kendo/2014.2.903/jquery.min.js"></script>
<script src="~/Scripts/kendo/2014.2.903/kendo.angular.min.js"></script>
<script src="~/Scripts/kendo/2014.2.903/kendo.all.min.js"></script>
<script src="~/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<div id="grid"></div>
<button type="button" id="btnOfflineMode">Offline</button>
<script>
$("#grid").kendoGrid({
columns: [
{ field: "Name" },
{ field: "Age" },
{ field: "NewCol" }
],
dataSource: [
{ Name: "John Doe", Age: 33 }
],
batch: true,
}).on('focus', function (e) {
var offset = $(this).offset();
var textarea = $("<textarea>");
textarea.css({
position: 'absolute',
opacity: 0,
top: offset.top,
left: offset.left,
border: 'none',
width: $(this).width(),
height: $(this).height()
})
.appendTo('body')
.on('paste', function () {
setTimeout(function () {
var value = $.trim(textarea.val());
var grid = $("#grid").data("kendoGrid");
var rows = value.split('\n');
var data = [];
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split('\t');
grid.dataSource.add({
Name: cells[0],
Age: cells[1],
NewCol: cells[2]
});
}
});
}).on('blur', function () {
});
setTimeout(function () {
textarea.focus();
});
});
$("#grid").attr("tabindex", -1).focus();
</script>
</body>
</html>
Manifest.cshtml:
CACHE MANIFEST
# version 1
CACHE:
/
/Content/kendo/2014.2.903/kendo.common.min.css
/Content/kendo/2014.2.903/kendo.default.min.css
/Content/kendo/2014.2.903/kendo.dataviz.min.css
/Content/kendo/2014.2.903/kendo.dataviz.default.min.css
/Scripts/kendo/2014.2.903/jquery.min.js
/Scripts/kendo/2014.2.903/kendo.all.min.js
/scripts/modernizr-2.6.2.js
FALLBACK:
/events /events.htm
NETWORK:
*
#{
Layout = null;
}
events.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Events</title>
<link rel="Stylesheet" href="/Content/style.css"
type="text/css" />
</head>
<body>
<section>
<h1>Events</h1>
<p>
The event listings are only available when
you are connected to the internet.
</p>
<div id="version">Version 1</div>
</section>
</body>
</html>
Try to create file site.maifest in the root folder of your site. And reference it in your html.
Like this
<html manifest="site.manifest">
Looks that it will be better to create your _Layout.cshtml logic and place common markup there.
I create an example where everything works good. Here it is on GitHub

Resources