Unexpected End of Expression when used with #Html.Raw(Model) - angularjs

I am trying to use AngularJs with ASP.NET MVC - this is my first attempt.
Index.html
#model string
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container" ng-init="courses = [{'name':'first'},{'name':'second'},{'name':'third'}]">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="course in courses">
<td>{{ course.name }}</td>
</tr>
</tbody>
</table>
_Layout.cshtml
<!DOCTYPE html>
<html ng-app>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/Scripts/angular.min.js"></script>
<title></title>
</head>
<body>
#RenderBody()
</body>
</html>
Above works fine and grid is displayed with Name as header and first, second and third as 3 rows. So my next step is to use
courses = #Html.Raw(Json.Encode(Model))
instead of
courses = [{'name':'first'},{'name':'second'},{'name':'third'}]
CourseController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace AngularJsMvc.Controllers
{
public class CoursesController : Controller
{
// GET: Courses
public ActionResult Index()
{
return View("Index", "", "[{'name':'first'},{'name':'second'}, {'name':'third'}]"); //This works fine when used with #Html.Raw(Model) in index.html
//return View("Index", "", GetCourses()); //This doesn't work when used with with #Html.Raw(Model) in index.html
}
public string GetCourses()
{
var courses = new[]
{
new Course { Name = "First" },
new Course { Name = "Second" },
new Course { Name = "Third" }
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() };
return JsonConvert.SerializeObject(courses, Formatting.None, settings);
}
}
public class Course
{
public string Name { get; set; }
}
}
This works fine if I use
return View("Index", "", "[{'name':'first'},{'name':'second'},{'name':'third'}]");
But if I use
return View("Index", "", GetCourses());
Then, below is the error I get. Please help - I have been struggling for almost entire day yesterday. I tried with or without Json.Encode
angular.min.js:123 Error: [$parse:ueoe]
http://errors.angularjs.org/1.6.4/$parse/ueoe?p0=courses%20%3D
at angular.min.js:6
"<div class="container" ng-init="courses = " [{\"name\":\"first\"},{\"name\":\"second\"},{\"name\":\"third\"}]""="">"

The following worked for me:
<div class="container" ng-init="courses = #Newtonsoft.Json.JsonConvert.DeserializeObject(Model)">
This also works:
<div class="container" ng-init="courses = #HttpUtility.HtmlDecode(Model)">
It's all about how angular treats the object it tries to parse and since you're passing an HTML decoded string it will treat as a string and therefore it won't be able to iterate threw it.

Related

Click flag to highlight issue

I have a table that lists various fields from a customer database. I'd like to add a new column with a grey flag (indicates no issues) If the user clicks the flag I'd like the flag to turn red (indicates there is an issue)
I'm using MVC, Angularjs and Font Awesome.
Could someone point me in the best direction please?
using System;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using Florence.Authentication;
using Florence.Data;
using Florence.Website.Models;
using Florence.Website.Models.Job;
namespace Florence.Website.Controllers
{
/// <summary>
/// </summary>
public class JobController : Controller
{
/// <summary>
/// Search jobs
/// </summary>
/// <returns>Job list</returns>
[AuthorizationFilter(PermissionList = "CanListJobs")]
public ActionResult Index()
{
return View("~/views/job/index.cshtml");
}
[AuthorizationFilter(PermissionList = "CanViewJobs", AllowLocalRequests = true)]
public ActionResult PdfView(int id)
{
using (var context = new FlorenceContext())
{
var job = context.Jobs
.Include(c => c.Customer)
.Include(c => c.Customer.Address)
.First(c => c.Id == id);
if (!HttpContext.Request.IsLocal && job.BelongsToCompanyId != DataBag.LoggedOnCompany.Id)
{
return new HttpUnauthorizedResult();
}
return View("~/views/job/pdf/view.cshtml", job);
}
}
It depends on your table structure, but you need to create either a new property in your array, for each row, or a new array with the same length as the original one. Then simply add a new column and detect any changes to that new property/array.
Here is a simple demo (click on text Icon to change the flag):
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.array = [
{"ID":12345,"Details":"ABC"},
{"ID":23456,"Details":"BCD"},
{"ID":34567,"Details":"CDE"},
{"ID":45678,"Details":"DEF"}
];
// a new array of the same length (a `map` of it)
$scope.flags = $scope.array.map(function(_){return false;});
$scope.submit = function(){
console.log($scope.flags); // (extra)
}
});
table, th, td {
border: 1px solid black;
}
.red {
color: red;
}
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form ng-submit="submit()">
<table>
<tr>
<th ng-repeat="(key,value) in array[0]">
{{key}}
</th>
<th>
Flag
</th>
</tr>
<tr ng-repeat="data in array">
<td ng-repeat="(key,value) in data">
{{value}}
</td>
<td>
<span ng-click="flags[$index] = !flags[$index]">
<i ng-class="{'red':flags[$index]}">Icon</i>
</span>
</td>
</tr>
</table>
<!-- (extra) -->
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>

Display all childs in Firebase Database (Web)

So I successfully displaying 1 database from my firebase using limitToLast function. Here is the webpage look like
Kinda curious how to display all of my databases (all childs from selected parent) from firebase console using javascript?
List of my database in firebase that I want to display
and here is my code below:
firebase.initializeApp(config);
var order = firebase.database().ref("order");
order.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
var submitOrder = function () {
var orderId = $("#orderOrderId").val();
var shipping = $("#orderShipping").val();
var subtotal = $("#orderSubtotal").val();
var total = $("#orderTotal").val();
};
order.limitToLast(1).on('child_added', function(childSnapshot) {
order = childSnapshot.val();
$("#orderId").html(order.orderId)
$("#shipping").html(order.shipping)
$("#subtotal").html(order.subtotal)
$("#total").html(order.total)
$("#link").attr("https://wishywashy-179b9.firebaseio.com/", order.link)
});
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/5.3.0/firebase.js"></script>
<script src="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/2.5.1/firebaseui.css" />
<!-- <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> -->
<!-- Load the jQuery library, which we'll use to manipulate HTML elements with Javascript. -->
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- Load Bootstrap stylesheet, which will is CSS that makes everything prettier and also responsive (aka will work on all devices of all sizes). -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<!-- <script type = "text/javascript" src = "data.js"></script> -->
<body>
<script type = "text/javascript" src = "data.js"></script>
<div class="container">
<h1>Merchant Portal</h1>
<h3>Order Lists</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Order ID</th>
<th>Shipping Price</th>
<th>Subtotal</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<!-- This is empty for now, but it will be filled out by an event handler in application.js with the most recent recommendation data from Firebase. -->
<td id="orderId"></td>
<td id="shipping"></td>
<td id="subtotal"></td>
<td id="total"></td>
</tr>
</tbody>
</table>
</body>
</html>
You will need to generate a new <tr> for each order. A very simple way to do this is simply generate the DOM elements in your on('child_added' callback:
var table = document.querySelector("tbody");
order.on('child_added', function(childSnapshot) {
order = childSnapshot.val();
var tr = document.createElement('tr');
tr.appendChild(createCell(order.orderId));
tr.appendChild(createCell(order.shipping));
tr.appendChild(createCell(order.subTotal));
tr.appendChild(createCell(order.total));
table.appendChild(tr);
});
As you can see, this code creates a new <tr> for each child/order, and populates that with simple DOM methods. It then adds the new <tr> to the table.
This code uses a simple helper function to handle the repetitious creating of <td> elements with a text node in them:
function createCell(text) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(text));
return td;
}

Displaying data using AngularJS

I am trying to represent some data taken from database in a table. I am using jersey as back-end and I have tested it in Postman that it works. The problem is I cannot display my data in the table in front-end, when I use AngularJS. It only shows me a blank table, without data at all. I am pretty new to AngularJS and I really want anyone of you to help me find the problem with my piece of code below.
list_main.js
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get('http://localhost:8080/BookCommerce/webapi/list').then(function(data){
$scope.bookList = data;
console.log($scope.bookList);
})
}
$scope.loadData();
})
index2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Of Books</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></s‌​cript>
<script src="js/list_main.js"></script>
</head>
<body>
<div class="row" data-ng-controller="ctrl" data-ng-app="app" data-ng-init="loadData()" style="margin: 10px;">
<div class="col-md-7">
<div class="panel panel-primary">
<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="exampleone">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="book in bookList">
<td>{{book.book_id}}</td>
<td>{{book.book_title}}</td>
<td>{{book.book_author}}</td>
<td>{{book.book_description}}</td>
<td>{{book.book_price}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
ListDAO.java
public class ListDAO {
public List<Book> findAll() {
List<Book> list = new ArrayList<Book>();
Connection c = null;
String sql = "SELECT * FROM book";
try {
c = ConnectionHelper.getConnection();
Statement s = c.createStatement();
ResultSet rs = s.executeQuery(sql);
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
ConnectionHelper.close(c);
}
return list;
}
protected Book processRow(ResultSet rs) throws SQLException {
Book book = new Book();
book.setBook_id(rs.getInt("book_id"));
book.setBook_title(rs.getString("book_title"));
book.setBook_author(rs.getString("book_author"));
book.setBook_description(rs.getString("book_description"));
book.setBook_price(rs.getInt("book_price"));
return book;
}
}
ListResource.java
#Path("/list")
public class ListResource {
ListDAO dao=new ListDAO();
#GET
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Book> findAll() {
System.out.println("findAll");
return dao.findAll();
}
}
Please help me. Thank you!
Okay this is much better than the last time,
There's still some bits wrong with your JS - it should look like this :
// Code goes here
var baseUrl = "https://demo5019544.mockable.io/";
angular.module('app', [])
.controller('ctrl', function($scope, $http){
$scope.bookList = [];
$scope.loadData = function(){
$http.get(baseUrl + 'BookCommerce/webapi/list').then(function(data){
$scope.bookList = data.data;
})
}
})
I made a demo REST service at : https://demo5019544.mockable.io/BookCommerce/webapi/list
which produces the kind of output your web service should product, I tested the code with this web service and with the tweaks I made it worked -- Yay.
The last thing I'd do now is check that your web service is throwing out the same / similar output that my mock is producing.

Trying to populate data in ASP.Net controller and fetch it view using angularjs

I am trying to populate data through controller and display it in view using angular js. I am using a function to return JSON data and use the data in the view.However i am not getting the data due to some error.
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Angular4DotnetMvc.Controllers
{
public class CourseController : Controller
{
// GET: Course
public ActionResult Index()
{
return View("Index","",GetCourses());
}
private object GetCourses()
{
var courses = new []{
new CourseVm {Number = "1", Name = "Science", Instructor= "Sai"},
new CourseVm {Number = "2", Name = "Geography", Instructor= "Ram"}
};
var settings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver()};
return JsonConvert.SerializeObject(courses, Formatting.None, settings);
}
}
public class CourseVm
{
public string Number { get; set; }
public string Name { get; set; }
public string Instructor { get; set; }
}
}
Index.cshtml
#model string
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container" ng-app>
<div class="row">
<table class="table table-condensed table-hover">
<tr ng-init="courses = #Html.Raw(Model)">
<th>Course</th>
<th>Course Name</th>
<th>Instructors</th>
</tr>
<tr ng-repeat="course in courses">
<td>{{course.Number}}</td>
<td>{{course.Name}}</td>
<td>{{course.Instructor}}</td>
</tr>
</table>
</div>
</div>
Layout.cshtml
<html>
<head>
<title>Angular4DotNet</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<script src="~/Scripts/jQuery/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap/bootstrap.js"></script>
<link href="~/Scripts/bootstrap/bootstrap.min.css" rel="stylesheet" />
<link href="~/Scripts/bootstrap/bootstrap.css" rel="stylesheet" />
#RenderSection("JavaScriptInHeader",required:false)
</head>
<body ng-app>
#RenderBody()
</body>
</html>
I am getting the following error:
Error: [$parse:ueoe] http://errors.angularjs.org/1.6.1/$parse/ueoe?p0=courses%20%3D%20%5B%7B
Why the data binding not happening?
The error is :
I am not sure why ="" after "instructor":"ram"}] is being added in the end in #Html.Raw(Model). i believe because of this it fails and agular cannot parse.
I would do on this way:
Create an action just to return the json content:
// GET: Course
public ActionResult Index()
{
return View();
}
public ActionResult GetCourses()
{
var courses = new []{
new CourseVm {Number = "1", Name = "Science", Instructor= "Sai"},
new CourseVm {Number = "2", Name = "Geography", Instructor= "Ram"}
};
return Json(courses, JsonRequestBehavior.AllowGet)
}
Then create an Angular controller:
angular.module('yourApp').controller('CoursesCtrl', ['$scope',function($scope)
{
$scope.courses = [];
$scope.loadCourses = function () {
$http.get('/Course/GetCourses').then(function (response) {
$scope.courses = response.data;
}, function (data) {
//error
});
}
}]);
After that insert the controller in the view:
<div class="container" ng-app="yourApp">
<div ng-controller="CoursesCtrl">
<div class="row">
<table class="table table-condensed table-hover" data-ng-init="loadCourses();">
<tr>
<th>Course</th>
<th>Course Name</th>
<th>Instructors</th>
</tr>
<tr ng-repeat="course in courses">
<td>{{course.Number}}</td>
<td>{{course.Name}}</td>
<td>{{course.Instructor}}</td>
</tr>
</table>
</div>
</div>
</div>
I hope this can help you.

Binding Viewbag Data to Angular JS

I have a List in my controller which is being of type Student(class in the model)
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
List<Student> obj = new List<Student>() {
new Student() { ID=1,Name="titi",Address="bbsr"},
new Student() { ID=1,Name="titi1",Address="bbsr"},
new Student() { ID=1,Name="titi2",Address="bbsr"}
};
ViewBag.data = obj;
return View();
}
}
I am using Angular JS (Beginner to Angular JS)
<html>
<head>
<title>Index</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="EFView">
#{ var a = ViewBag.data;}
<div ng-init="init(#Html.Raw(a)">
<table>
<tr ng-repeat="x in a">
<td >
{{x.ID}}
</td>
<td>
{{x.Name}}
</td>
<td>
{{x.Address}}
</td>
</tr>
</table>
</div>
</body>
</html>
Not getting the output as expected.. where & what I am missing, I tried with all trial

Resources