Cannot read property 'price' of undefined in VueJs Application - node.js

I am creating shopping cart system by using vueJs. I want to display the list of item that user want to by but when I run the application and try to add product in checkout list ,I am getting following errors in google chrome console windows when I want to add the item into list.
[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"
(found in <Root>)
warn # vue.js:634
vue.js:1897 TypeError: Cannot read property 'name' of undefined
at eval (eval at createFunction (vue.js:11628), <anonymous>:3:265)
at Proxy.renderList (vue.js:2658)
at Proxy.eval (eval at createFunction (vue.js:11628), <anonymous>:3:183)
at Vue._render (vue.js:3545)
at Vue.updateComponent (vue.js:4061)
at Watcher.get (vue.js:4472)
at Watcher.run (vue.js:4547)
at flushSchedulerQueue (vue.js:4305)
at Array.<anonymous> (vue.js:1989)
at flushCallbacks (vue.js:1915)
logError # vue.js:1897
cart.html:91 Uncaught (in promise) TypeError: Cannot read property 'price' of undefined
at cart.html:91
Here is my cart.html code .
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="bootstap.css">
<!--<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>-->
<!--<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js">
</script>
</head>
<body>
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="index.html">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link" href="index.html">Show All Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/AddProducts.html">Add Product</a>
</li>
<li class="nav-item">
<a class="nav-link" href="cart.html"> cart</a>
</li>
</ul>
</nav>
<br />
<div class="container" id="app">
<h2>Your cart</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>quantity</th>
<th>Rate</th>
<th>vendor</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr v-for="cartItem in cartItems">
<td>{{cartItem.product.name}}</td>
<td>
<button type="button" class="btn btn-primary" v-on:click="changequantity(cartItem.productId,-1)">-</button>
{{cartItem.quantity}}
<button type="button" class="btn btn-primary" v-on:click="changequantity(cartItem.productId,+1)">+</button>
</td>
<td>{{cartItem.product.price}}</td>
<td>{{cartItem.product.vendor.name}}</td>
<td>{{cartItem.quantity*cartItem.product.price}}</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td><b>Total</b></td>
<td>{{this.totalPrice}}</td>
</tr>
</tbody>
</table>
</div>
<script>let app = new Vue({
el: "#app",
data: {
totalPrice: 0,
price: 0,
cartItems:[]
},
methods:{
fetAllcartItems(){
new Promise((resolve)=>{
axios.get('/api/cart').then(function (response) {
resolve(response.data)
})
}).then((data)=>{
console.log(data)
this.cartItems=data
// console.log(data)
for(d in data){
this.totalPrice = this.totalPrice+ (d.quantity )* (d.product.price);
}
// console.log(this.products)
})
},
changequantity(id,quantity){
var obj = {id : id , quantity: quantity}
// let iddd = parseInt(id)
console.log(this.cartItems)
let index =this.cartItems.findIndex(item => item.productId == id)
this.totalPrice = this.totalPrice + this.cartItems[index].product.price * quantity
if(this.cartItems[index].quantity ===1 && quantity===-1){
this.cartItems.splice(index ,1);
}
new Promise((resolve)=>{
axios.post('/api/cart/add',obj).then(function (response) {
resolve(response.data)
})
}).then((data)=>{
console.log(data)
if(data.quantity>0)
this.cartItems[index].quantity = data.quantity
/*for(d of data){
this.totalPrice = this.totalPrice+ (d.quantity )* (d.product.price);
}*/
})
// location.reload();
}
}
})
app.fetAllcartItems();</script>
</body>
</html>
Here is the screen shot when I clicked the buy button.
Here is the screen shot when I run the applications..

To see why name is showing you need to check which data you are getting, check it on VueDevtool or else make put console.log(this.cartItems) on a proper place and see how its related , make sure that in this object cartItems is an array of object where poduct is also object and name has value/null.
Also for(d in data) , replace with for(let d in data)

for(d in data){ seems almost certainly wrong. Perhaps you meant for(const d of data) {? In its original form d is a string key, not the item in the array. That's plausibly the cause of the second error, the one about price.
For the error about name I would guess it's this:
<td>{{cartItem.product.vendor.name}}</td>
It looks like cartItem.product.vendor is undefined in some cases.
I strongly suggest you start using a linter. Your code is full of other small defects that I would expect a linter to pick up for you.
For starters, you shouldn't be creating all those new promises.

Related

How to make my update button work correctly

I am making a todolist app using express, mongoose, mongodb, bootstrap. When I hit my update button to update a task it just makes a duplicate of the task that i'm trying to update. How would I go about making my update button update the original task?
Here are some screenshots on what happens when I try to update :
https://i.stack.imgur.com/t11OG.jpg - here I created a task "make breakfast".
https://i.stack.imgur.com/ijt98.jpg - here I hit the yellow update button and I am updating the task from "make breakfast" to "make lunch".
https://i.stack.imgur.com/V4RCe.jpg - here when I hit the green update button it creates a separate task instead of updating the original "make breakfast" task.
My routes and my ejs for the home page are below:
I can also show the ejs for updating a task as well.
Thanks
const express = require("express");
const { route } = require("express/lib/application");
const router = express.Router();
const mongoose = require("mongoose");
const Todoinfo = require("../models/infoSchema");
router.get("/", async (req, res) => {
// get all todos
const allTodos = await Todoinfo.find({}).sort("-date");
res.render("home", { allTodos });
});
router.post("/", async (req, res) => {
// add a todo
const newTodo = new Todoinfo(req.body); // create a new todo
await newTodo.save((err) => {
// save the new todo
if (err) {
res.send("Not updated");
}
});
//res.redirect("/");
});
router.get("/:id/delete", async (req, res) => {
// delete a todo
const todoDelete = await Todoinfo.findByIdAndDelete(req.params.id); // find the todo by id and delete it?
res.redirect("/"); // redirect to home page
});
router.get("/:id/finish", async (req, res) => {
// finish a todo (change status to completed)
const todoDelete = await Todoinfo.findByIdAndUpdate(req.params.id, {
progress: "Completed",
});
res.redirect("/");
});
router.get("/:id/update", async (req, res) => {
// update a todo (change status to in progress)
const updateTodo = await Todoinfo.findById(req.params.id); // find the todo by id and update it?
res.render("update", { updateTodo }); // render the update page with the todo
});
router.get("/:id/update/final", async (req, res) => {
// update a todo (change status to finished)
const updateTodo = await Todoinfo.findByIdAndUpdate(req.params.id, {
// find the todo by id and update it?
description: req.body.description, // update the description of the todo with the new description
});
res.redirect("/");
});
module.exports = router;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Todo App</title>
</head>
<body>
<section class="vh-100" style="background-color: #eee ">
<div class="container py-5 h-100">
<div class="row d-flex justify-content-center align-items-center h-100">
<div class="col col-lg-12 col-xl-g">
<div class="card rounded-3">
<div class="card-body p-4">
<h4 class="text-center my-3 pb-3 text-primary ">My Todo App</h4>
<form class="row row-cols-lg-auto g-3 justify-content-center
align-items-center mb-4 pb-2" action="/" method="POST">
<div class="col-12">
<div class="form-outline">
<input type="text" id="form1" class="form-control" name="description" />
<label class="form-label" for="form1">Create a new task </label>
</div>
</div>
<div class="col-12">
<button type="submit" class="btn btn-primary mb-4">Add</button>
</div>
</form>
<table class="table mb-4">
<thead>
<tr>
<th scope="col">Item No.</th>
<th scope="col">Todo Item</th>
<th scope="col">Action</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
<% for(let i= 0; i <allTodos.length; i++) { %>
<tr>
<% let z= i + 1 %>
<th scope="row"><%= z %></th>
<% if (! allTodos[i].progress.localeCompare(" Completed" )) { %>
<td class="text-decoration-line-through"> <%=
allTodos[i].description %> </td>
<%} else {%>
<td> <%= allTodos[i].description %> </td>
<%}%>
<td> <%= allTodos[i].progress %> </td>
<td>
<button type="submit" class="btn btn-danger ms-1 mb-1">Delete</button>
<% if (! allTodos[i].progress.localeCompare(" Completed"))
{ %>
<%} else {%>
<a href="/<%= allTodos[i]._id %>/finish" class="text-decoration-none">
<button type="submit" class="btn btn-success ms-1 mb-1">Finished</button></a>
<button type="submit" class="btn btn-warning ms-1 mb-1">Update</button>
<% } %>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>

CORS-Error / using hosted file with datatables?

i want to read this txt-file using datatables.net
https://www.rapidtech1898.com/aaadownload/arrays.txt
But when i want to use the file with the following files the output is not working i have this error in the chrome inspector:
(datatables is not reading as it sould and the inspector shows me that)
(at first i had the txt-file locally and read that there are some problems with that using chrome with local file - but this is a "normal" http-link isn´t it? - why is this stil not working as expected?
I also tried to do the same thing locally before - but i get the same error:
I have an index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
<div class="container py-5">
<header class="text-center text-white">
<h1 class="display-4">Levermann Scores</h1>
</header>
<div class="row py-5">
<div class="col-lg-10 mx-auto">
<div class="card rounded shadow border-0">
<div class="card-body p-5 bg-white rounded">
<div class="table-responsive">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="mainAJAX.js"></script>
</body>
</html>
And this is the mainAJAX.js file:
$(document).ready(function() {
$('#example').DataTable( {
// "ajax": "http://localhost:2121/arrays.txt"
"ajax": "https://www.rapidtech1898.com/aaadownload/arrays.txt"
} );
} );
Somebody told me - that if also the server is hosted on the same domain (like rapidtech1898.com) it would probably work. But is there no way to test such think locally before deploying this somewhere else?
For reasons of security, that is how CORS works. You cannot request data from a different origin unless the server allows it. However, for the purpose of development, you can disable CORS in multiple ways. There is a nice article for it here. But my personal favourite is this solution (to use a proxy that doesn't bypasses CORS):
fetch('https://cors-anywhere.herokuapp.com/https://www.rapidtech1898.com/aaadownload/arrays.txt', {
method: "GET",
headers: {
"Content-type": "application/json;charset=UTF-8",
"x-requested-with": "localhost:3000"
}
}).then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));
I think i found the problem -
In the server-js i have to usse express.static for the data-folder:
const express = require("express");
const app = express();
app.use(express.static('data'))
app.listen(2121, () => {
console.log("Server is running on port 2121...");
});
And in the datafolder i have to put all files (index.html, mainAJAX.js and arrays.txt).
Then i can call the text-file in the mainAJAX.js like that:
$(document).ready(function() {
$('#example').DataTable( {
"ajax": "arrays.txt"
} );
} );

Nested URLs not working with requirejs

Using requirejs, I can use simple routes like /register, but I always get an error when I try a nested route like /register/1 or something.
This works (where the route is just /register):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register') {
console.log("Got it") // This works since the route is just '/register'
}
})
This does not work (where the route is /register/1):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register/1') {
console.log("Got it") // Error
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/style.css">
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/registration.css">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<script
type="text/javascript"
src="/javascripts/styles/js.cookie.js">
</script>
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
</head>
<body>
<div id="my-app"></div>
</body>
</html>
config.js
requirejs.config({
baseUrl: 'javascripts/views',
paths: {
allConversations: 'allConversations',
conversation: 'conversation',
home: 'home',
layout: 'layout',
loginView: 'login',
login: '../scripts/login',
logoutHandler: '../scripts/logout',
memberProfile: 'memberProfile',
profile: 'profile',
register: 'register',
conversationCount: 'conversationCount',
nav: 'nav',
axios: '//unpkg.com/axios/dist/axios.min',
jquery: [
'//code.jquery.com/jquery-3.3.1.min',
'//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
],
bootstrap: ['//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min'],
fontAwesome: ['//use.fontawesome.com/7973784de3'],
},
})
require([
'home',
'layout',
'loginView',
'login',
'logoutHandler',
'nav',
'register'
])
How do I use nested URL routes with requirejs?
First problem. You are loading config module twice. data-main attribute specifies what modules should be loaded after the RequireJS load. So the second line is basically a duplicate of this
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
Please replace this with just
<script data-main="config" src="require.js"></script>
Second problem, you have syntax error in layout.js. Your syntax looks like JSX, not regular JavaScript. Please amend this or use RequireJS JSX files loader plugin -> https://github.com/philix/jsx-requirejs-plugin
Can you please show use you config module?
Cheers.

Uncaught ReferenceError: kendo is not defined. Binding the grid fails

I am creating a MVC 5 application using kendo MVC grid. The data that i am pulling from the database is not binding to the grid. When I check the developer controls is see error Uncaught ReferenceError: kendo is not defined. I have also noticed that the action method specified in the grid doesnt fire. Looks like a jquery issue.
I have checked all my references and done the basic set to run kendo MVC. Not sure what the problem is
#model IEnumerable<CC.GRP.MCRequest.Models.TeamIn>
#(Html.Kendo().Grid<CC.GRP.MCRequest.Models.TeamIn>()
.Name("GridTeam")
.Columns(columns =>
{
columns.Bound(o => o.TeamID).Groupable(false);
columns.Bound(o => o.CountryCode);
columns.Bound(o => o.TeamName);
columns.Bound(o => o.TeamDescription);
})
.Pageable()
.Sortable()
.Filterable()
.Scrollable()
.Groupable()
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("Team_Read", "Admin"))
)
)
Controller code
public ActionResult Team()
{
return View();
}
public ActionResult Team_Read([DataSourceRequest]DataSourceRequest request)
{
return Json(mcrRepository.GetTeams().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
Bundle.config
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/kendo").Include(
"~/ Scripts/kendo/2017.1.223/jquery.min.js",
"~/ Scripts/kendo/2017.1.223/jszip.min.js",
"~/Scripts/kendo/2017.1.223/kendo.all.min.js",
"~/Scripts/kendo/2017.1.223/kendo.aspnetmvc.min.js"));
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.min.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/custom/css").Include(
"~/Content/custom/app.css"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/Site.css",
"~/Content/bootstrap.css"
));
bundles.Add(new StyleBundle("~/Content/kendo/css").Include(
"~/Content/kendo/2017.1.223/kendo.common.min.css",
"~/Content/kendo/2017.1.223/kendo.mobile.all.min.css",
"~/Content/kendo/2017.1.223/kendo.dataviz.min.css",
"~/Content/kendo/2017.1.223/kendo.default.min.css",
"~/Content/kendo/2017.1.223/kendo.dataviz.default.min.css"
));
bundles.IgnoreList.Clear();
}
Layout.cshtm
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0,user-scalable=no">
#Styles.Render("~/Content/kendo/css")
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/custom/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img src="~/Images/Computacenter.png" />
<h1>MCR</h1>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right text-center">
<li><span class="glyphicon glyphicon glyphicon-home" aria-hidden="true"></span><p>Home</p></li>
<li><span class="glyphicon glyphicon glyphicon-file" aria-hidden="true"></span><p>Requests</p></li>
<li><span class="glyphicon glyphicon glyphicon-tasks" aria-hidden="true"></span><p>Activities</p></li>
<li><span class="glyphicon glyphicon glyphicon-file" aria-hidden="true"></span><p>Reports</p></li>
<li class="hideli"><span class="glyphicon glyphicon glyphicon-cog" aria-hidden="true"></span><p>Admin</p></li>
<li><span class="glyphicon glyphicon glyphicon-save" aria-hidden="true"></span><p>Save View</p></li>
</ul>
</div>
</div>
</nav>
</header>
<div id="body">
#RenderBody()
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/kendo")
#RenderSection("scripts", required: false)
</body>
</html>
This has been fixed. It was as simple as closing and opening visual studio.

FlexSlider not working with MVC5 Framework

I am creating a website using MVC5 (we do for all our websites here) and I am trying to integrate the FlexSlider (found here: https://woocommerce.com/flexslider/) into one of my pages.
I can't seem to get it working, the page just displays nothing, yet it appears in the 'Inspect Element' with each image as being 0x0 px.
HTML:
<div class="flexslider" data-controlnav="thumbnails">
<ul class="slides">
#if (Model.CDSContent != null)
{
foreach (var item in Model.CDSContent)
{
<li>
<a href="#">
<img src="#Html.Raw(item["newsimage"])" alt="Slide 2">
<div class="flex-caption">newstitle</div>
</a>
</li>
}
}
</ul>
</div>
I also have the JS and CSS linked:
<link rel="stylesheet" type="text/css" href="http://flexslider.woothemes.com/css/flexslider.css">
<link rel="stylesheet" type="text/css" href="http://lab.mattvarone.com/projects/jquery/totop/css/ui.totop.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.flexslider.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.easing.js"></script>
<script type='text/javascript' src="http://flexslider.woothemes.com/js/jquery.mousewheel.js"></script>
<script type='text/javascript' src="http://lab.mattvarone.com/projects/jquery/totop/js/jquery.ui.totop.js"></script>
Of course its a little bit difficult to say why your code is not working.
Have you checked what #Html.Raw(item["newsimage"]) returns ?
But...
You could use a carousel that runs on bootstrap.
The code below i made is to scan a folder for images and then i send them to the view with a viewbag.
--Controller code Start--
var GetSliderImaged = Directory.EnumerateFiles(Server.MapPath("~/Content/SlideShowIndexPage")).Select(fn => Path.GetFileName(fn));
ViewBag.Sliderimages = GetSliderImaged;
--Controller code End--
--View code Start--
<div id="myCarousel" class="carousel slide MTop10 BRadius10 unselectable" data-ride="carousel" data-interval="6000">
<ol class="carousel-indicators" style="margin-bottom: 0px;">
#{
var ii = 0;
foreach (var image in ViewBag.Sliderimages)
{
if (ii == 0)
{
<li data-target="#myCarousel" data-slide-to="#ii" class="active"></li>
}
else
{
<li data-target="#myCarousel" data-slide-to="#ii"></li>
}
ii++;
}
}
</ol>
<div class="carousel-inner " role="listbox">
#{
var i = 0;
foreach (var image in ViewBag.Sliderimages)
{
if (i == 0)
{
<div class="item active">
<img src="~/Content/SlideShowIndexPage/#image" alt="#image" title="#image" class="img-responsive AWIndexPageSlideImage" />
<div class="carousel-caption">
</div>
</div>
i++;
}
else
{
<div class="item">
<img src="~/Content/SlideShowIndexPage/#image" alt="#image" title="#image" class="img-responsive AWIndexPageSlideImage" />
<div class="carousel-caption">
</div>
</div>
}
}
}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
--View code End--
Just so you know .. the code is not complete but its works for sure if there are images "It does not check if there are no images in the viewbag etc"
But for sure that will be easy to make it yourself.

Resources