I am using visual studio serenity template for my aspnet MVC application. For example what I want to do is to generate random values at every 1 second in controller and pass it to cshtml page <div>.
Please help me how can I refresh my page at every 1 second.
[RoutePrefix("Dashboard"), Route("{action=index}")]
public class DashboardController : Controller
{
[Authorize, HttpGet, Route("~/")]
public ActionResult Index()
{
return View();
}
model Serene2.Common.DashboardPageModel
#{
ViewData["Title"] = "Dashboard";
ViewData["PageId"] = "Dashboard";
}
#section Head {
<link rel="stylesheet" href="~/Content/iCheck/flat/blue.css">
<link rel="stylesheet" href="~/Scripts/morris/morris.css">
<link rel="stylesheet" href="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.css">
<link rel="stylesheet" href="~/Scripts/datepicker/datepicker3.css">
<link rel="stylesheet" href="~/Scripts/daterangepicker/daterangepicker-bs3.css">
<link rel="stylesheet" href="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.min.css">
<script src="~/Scripts/raphael/raphael-min.js"></script>
<script src="~/Scripts/morris/morris.min.js"></script>
<script src="~/Scripts/sparkline/jquery.sparkline.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="~/Scripts/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script src="~/Scripts/knob/jquery.knob.js"></script>
<script src="~/Scripts/daterangepicker/moment.min.js"></script>
<script src="~/Scripts/daterangepicker/daterangepicker.js"></script>
<script src="~/Scripts/datepicker/bootstrap-datepicker.js"></script>
<script src="~/Scripts/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js"></script>
<script src="~/Scripts/adminlte/pages/dashboard.js"></script>
<script src="~/Scripts/adminlte/demo.js"></script>
}
#section ContentHeader {
<h1>#LocalText.Get("Navigation.Dashboard")<small>#Html.Raw(Texts.Site.Dashboard.ContentDescription)</small></h1>
}
<div class="inner">
<p>My Random Value From Controller</p>
</div>
hey with ajax you can easily achieve that,
The main issue is such approach will lead to infinite recursive loop so handle with care.Anyway your code should be like below
1.In cshtml
<p id="pValue"></p>
2. In script
var someRootPath = "#Url.Content("~")";
(function randomGenerator() {
$.ajax({
url: someRootPath + 'Dashboard/GetRandomValue',
success: function (data) {
$('#pValue').html(data.someValue);
},
complete: function () {
setTimeout(randomGenerator, 1000);
}
});
})();
and finally
3.Controller
[HttpGet]
public JsonResult GetRandomValue()
{
return Json(new { someValue = Guid.NewGuid().ToString() }, JsonRequestBehavior.AllowGet);
}
Hope this will help according to your current scenario.
If you want to refresh your page every second, you could put some javascript on the page like:
<script type="text/javascript">
setTimeout(function(){ document.location.reload(); }, 1000);
</script>
If you only want to update part of the page, you can make an ajax call (http://api.jquery.com/jquery.ajax/ or https://developer.mozilla.org/nl/docs/Web/API/XMLHttpRequest) which would point to your controller action - returning only the necessary data. Then, with javascript again, you can modify the parts of the page you find relevant.
Related
I'm trying to get some dynamic content to display based on UTMs in my URL. While I can call the function in the browser to get the content to display, it isn't doing so on page load. (Function works, but my timing must be off)
I've tried to change the order in which I call jQuery and my JS file, but either way it doesn't show unless I paste my function into chrome dev tools.
Here's the relevant part of the function:
// regex to find the URL param above
var dynamicContent = getParameterByName('dc');
$(document).ready(function() {
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
And the HTML:
<span id="default-content" class="dynamic-content">Tech</span>
<span id="fintech" class="dynamic-content">Fintech</span>
<span id="martech" class="dynamic-content">Martech</span>
<!-- excluded remaining options -->
And here's my header in case there's a different way I should be calling everything:
<head>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="assets/dynamic.js" type="text/javascript"></script>
</head>
Again, as copying/pasting my code into dev tools after the page load works, how do I time it so that this function runs on page load?
Thanks.
Maybe try this:
$(window).on('load', function () {
var dynamicContent = getParameterByName('dc');
if (dynamicContent == 'fintech') {
$('#fintech').show();
}
else if (dynamicContent == 'martech') {
$('#martech').show();
}
//... excluded remaining options
else {
$('#default-content').show();
}
});
I am trying to incorporate a Javascript function (contained in app.js), which I am trying to run from the index.html of my Angular 2 application.
Initially I used a CLI program called Office Add-in generator to make a non-angular application, in which this JavaScript works.
However when using the Add-in generator in an Angular application the app.js file is not automatically generated. Manually copy pasting the app.js file and <script> link does not work either. I realise I have only provided a couple of files worth of code, let me know if I should edit more in, or provide a github link?
The error in chrome is net::ERR_ABORTED not defined with a 404 message. (relating to the app.js file)
~~~~HTML~~~~~
<head>
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.css">
<link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.css">
<meta charset="utf-8">
<title>Microsoft Graph Connect sample</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/Office.js" type="text/javascript"></script>
<script>
window.history.replaceState = function(){};
window.history.pushState = function(){};
</script>
</head>
<body>
<app-root></app-root>
<button onclick="setItemBody()">Paste to email</button>
<script type="text/javascript" src="node_modules/core-js/client/core.js"></script>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.js"></script>
<script type="text/javascript" src="node_modules/office-ui-fabric-js/dist/js/fabric.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
~~~~~~~app.js~~~~~~~~
var item;
Office.initialize = function () {
item = Office.context.mailbox.item;
// Checks for the DOM to load using the jQuery ready function.
$(document).ready(function () {
// After the DOM is loaded, app-specific code can run.
// Set data in the body of the composed item.
// setItemBody();
});
}
// Get the body type of the composed item, and set data in
// in the appropriate data type in the item body.
function setItemBody() {
item.body.getTypeAsync(
function (result) {
if (result.status == Office.AsyncResultStatus.Failed){
write(result.error.message);
}
else {
// Successfully got the type of item body.
// Set data of the appropriate type in body.
if (result.value == Office.MailboxEnums.BodyType.Html) {
// Body is of HTML type.
// Specify HTML in the coercionType parameter
// of setSelectedDataAsync.
item.body.setSelectedDataAsync(
'<b>These are the times I am available:</b><br>Monday -- 8:30 to 9:00<br>Tuesday -- 1:00 to 5:00<br>Thursday -- 4:00 to 5:00<br>',
{ coercionType: Office.CoercionType.Html,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
else {
// Body is of text type.
item.body.setSelectedDataAsync(
' Kindly note we now open 7 days a week.',
{ coercionType: Office.CoercionType.Text,
asyncContext: { var3: 1, var4: 2 } },
function (asyncResult) {
if (asyncResult.status ==
Office.AsyncResultStatus.Failed){
write(asyncResult.error.message);
}
else {
// Successfully set data in item body.
// Do whatever appropriate for your scenario,
// using the arguments var3 and var4 as applicable.
}
});
}
}
});
}
// Writes to a div with id='message' on the page.
function write(message){
document.getElementById('message').innerText += message;
}
Actually you should not just put your js files in index.html better add in .angular-cli.json file.. and about js not working in ng2+ project.. check out https://angular.io/guide/attribute-directives I think you must make wrapper. check this as well https://medium.com/#NetanelBasal/typescript-integrate-jquery-plugin-in-your-project-e28c6887d8dc
I am trying to implement Modal popup on an image click by using Bootstrap Lightbox, but I'm not able to achieve the same. I followed an example which has identical code as below. I have downloaded the Lightbox components(*.lightbox.js and *.lightbox.css) and placed in the directory where my below HTML file resides. Can someone please help me out in fixing this issue.
<!doctype html>
<html ng-app="myApp">
<head>
<title>Sandesh</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script src="angular-bootstrap-lightbox.js"></script>
<link rel="stylesheet" href="angular-bootstrap-lightbox.css">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
</head>
<body ng-controller="GalleryCtrl">
<ul>
<li ng-repeat="image in images">
<a ng-click="openLightboxModal($index)">
<img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
</a>
</li>
</ul>
<script>
var app = angular.module('myApp',['bootstrapLightbox'])
.controller('GalleryCtrl', function ($scope, Lightbox) {
$scope.images = [
{
'url': '9RyWebbb.jpg',
'thumbUrl': 'Thumb_9RyWebbb.jpg'
}
];
$scope.openLightboxModal = function (index) {
Lightbox.openModal($scope.images, index);
};
});
</script>
</body>
</html>
First, confirm that the name of the modu:le is "bootstrapLightbox". If it actually is, import it in the module via:
var app = angular.module('myApp',['bootstrapLightbox']);
Determine if you want to define controllers, services and directives against the variable, or against the methods:
var app = angular.module('myApp',['bootstrapLightbox']);
app.controller('GalleryCtrl', function ($scope, Lightbox) {
// etc
});
or
angular.module('myApp',['bootstrapLightbox'])
.controller('GalleryCtrl', function ($scope, Lightbox) {
// etc
});
Then, this maybe is less important, but a good tip to show: if you use some object only inside your JS code, without affecting directly the DOM, better use plain variables instead of declaring them on the $scope. Here, you use $scope to declare an array or "image" objects, but then only use it inside your lightbox instead of directly using it in the DOM.
So, I'd turn this...
$scope.images = [
{
'url': '9RyWebbb.jpg',
'thumbUrl': 'Thumb_9RyWebbb.jpg'
}
];
$scope.openLightboxModal = function (index) {
Lightbox.openModal($scope.images, index);
};
... into this:
var images = [
{
'url': '9RyWebbb.jpg',
'thumbUrl': 'Thumb_9RyWebbb.jpg'
}
];
$scope.openLightboxModal = function (index) {
Lightbox.openModal(images, index);
};
I hope it was useful for you!
Problem solved on including additional files as mentioned below:
<!doctype html>
<html ng-app="myApp">
.....
<link rel="stylesheet" type="text/css" href="ui-bootstrap-csp.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.3/ui-bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-bootstrap/1.3.3/ui-bootstrap-tpls.min.js"></script>
....
....
</html>
Also note that the order in which we include these files also matters; for example in this case the pop-up functionality doesn't work if we add 'ui-bootstrap-tpls.min.js' before 'ui-bootstrap.min.js'
Anyways thanks all for your valuable suggestions :)..cheers!
I have a bunch of web pages where I have an identical construct:
<html>
<head>
<script src="sorttable.js"></script>
<noscript>
<meta http-equiv="refresh" content="60">
</noscript>
<script type="text/javascript">
<!--
var sURL = unescape(window.location.pathname);
function doLoad()
{
setTimeout( "parent.frames['header_frame'].document.submitform.submit()", 60*1000 );
}
function refresh()
{
window.location.href = sURL;
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.replace( sURL );
}
//-->
</script>
<script type="text/javascript">
<!--
function refresh()
{
window.location.reload( true );
}
//-->
</script>
</head>
<body>
.
.
.
<script type="text/javascript">
window.onload = function() { sorttable.innerSortFunction.apply(document.getElementById("OpenFace-2"), []); doLoad(); }
</script>
</body>
</html>
This works perfectly in every page except for one, where when the onload function runs it cannot find the sorttable code (which is loaded from sorttable.js up at the top). All these pages are part of the same application and are all in the same dir along with the js file. I do no get any errors in the apache log or the js console until that page loads, when I get:
sorttable.innerSortFunction is undefined
I can't see what makes this one page different. Can anyone see what is wrong here, or give me some pointers on how I can debug this further?
The code I pasted in is from the source of the page where it does not work, but it is identical as the pages where it does work.
Looks like on that page the table with id OpenPhace-2 by which you try to sort have no needed class: sortable
The function innerSortFunction of sorttable object will be present only if there is any table with sortable class exists.
If i have such javascript in my razor veiw:
#{
Grid grid = #Model.GetGridFromModel();
Bool isSomething = #Model.GetSomething();
Bool isSomethingMore = #Model.GetSomehtingMore();
Bool isSomethingElse = #Model.GetSomethingElse()
int caseCount = 0;
}
$(document).ready(function () {
$("#tabs").tabs({
show: function (event, ui) {
switch (ui.index) {
#if (isSomething){
<text>
case #caseCount:
change('#grid.Avalue');
break;
</text>
caseCount++;
}
#if(isSomethingElse){
<text>
case #caseCount:
change('#grid.Bvalue');
break;
</text>
caseCount++;
}
#if (isSomethingElseMore){
<text>
case #caseCount:
change('#grid.Cvalue');
break;
</text>
}
}
}
});
funciton change(id)
{
//doing somehting;
}
So i want to put that javascript in separate file and reference that file to my view, and the problem is how may i pass values from razor to javascript when javascript in separate file?
Javascript are files without being parsed by the compiler, so, you have no chance...
What you can do however is to use a dynamic javascript, for example:
<script src="/CustomScripts/scripts.js"><script>
Have a route that says:
routes.MapRoute(
"CustomScripts", "CustomScripts/{id}",
new { controller = "Scripts", action = "GetFile" }
);
Create your controler and use a simple return View(); like
public ActionResult GetFile(string id)
{
// use id as you please
// pass any Model you want
return View();
}
In that view, just put your javascript with Razor syntax.
Or you can use variables and load them up make the use of RenderSection()
in your _Layout.cshtml file add a section in your <head> before any other javascript
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
#RenderSection("script_variables", false)
<script src="#Url.Content("~/Scripts/jquery-1.6.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-2.0.6-development-only.js")" type="text/javascript"></script>
</head>
and in any View that you want to add such variables, just do:
#Section script_variables {
<script type="text/javascript">
var variableA = '#MyVarA',
variableB = '#MyVarB',
variableC = '#MyVarC';
</script>
}
And all other files that you load the script will have such code...
You might declare some js-variables on your page and then use those variables from the .js-file
You might call a function inside your .js-file and send your data as arguments
(Please consider creating one object and fill with your data instead of creating multiple variables.)