Hi I am learning WebApi in VS2015. I have some experience in MVC4 so i know concepts of Routing in MVC$. I am following http://www.c-sharpcorner.com/uploadfile/65794e/web-api-with-angular-js/ website. I am trying to display some data from database as below.
public class TestController : ApiController
{
// GET: api/Test
public WebAPI db = new WebAPI();
public IEnumerable<LoginTbl> Get()
{
return db.LoginTbls.AsEnumerable();
}
}
WebApiConfig.cs as below.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Test}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Service.Js code.
app.service("APIService", function ($http) {
this.getSubs = function () {
return $http.Get("")
}
}
);
I am not sure what to pass in $http.Get("")
This is my index.cshtml
#{
}
<style>
table, tr, td, th {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
}
</style>
<h2>Welcome to Sibeesh Passion's Email List</h2>
<body data-ng-app="APIModule">
<div id="tblSubs" ng-controller="APIController">
<table>
<tr>
<th>UserName</th>
<th>Password</th>
</tr>
<tbody data-ng-repeat="sub in subscriber">
<tr>
<td>{{sub.UserName}}</td>
<td>{{sub.Password}}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/APIScripts/Module.js"></script>
<script src="~/Scripts/APIScripts/Service.js"></script>
<script src="~/Scripts/APIScripts/Controller.js"></script>
I am using AngularJs as clientscript. I am not sure how to run the above application as i can see two RouteConfig.cs and WebAPiconfig.cs. Someone tell me which file i should change in order to run the application? Thank you...
In the tutorial you're following, they don't actually say what they named the API controller, but it is called SubscriberController. The route matches up with api/ and then the word before the word Controller - so, api/Subscriber in the tutorial, and api/Test in your case.
In your angular routing configuration, your code would become $http.get("api/Test");
In order to return JSON from Web API, we'll need this line of code in your WebApiConfig.cs :
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Related
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.
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"></script>
<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.
I want to refresh the API every 100 milli seconds ,can anyone help.
code takes data from api and displays in the table. Backend is updated from different sources ,so we are supposed to refresh the data every 100ms.
<html>
<head>
<title>Angular JS Includes</title>
<style>
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f2f2f2;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h2>AngularJS Cycle count application</h2>
<div ng-app="myApp" ng-controller="customersCtrl">
<table>
<tr>
<th>Item Number </th>
<th>UPC Number</th>
<th>Count Qnty</th>
</tr>
<tr ng-repeat="x in names">
<td>{{ x.ITEM }}</td>
<td>{{ x.UPC}}</td>
<td>{{ x.QNTY}}</td>
</tr>
</table>
</div>
<script
src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://54.244.108.186:4000/api/cc_detail")
.then(function (response) {
$scope.names = response.data.item_upc;
});
});
</script>
</body>
</html>
If you want to refresh your screen based on back end updates then ideally you should try to use HTML5 Server Sent Events rather then hitting a particular API every 100 milliseconds. Hitting the api every 100 milliseconds would create a new thread on the server to handle the request causing a bottleneck for other requests.....you would kind of be simulating a DOS attack.
HTML5 event source will create one connection with the server and would allow the server to push updates to the client whenever required instead of making multiple requests.
Refer to link http://www.w3schools.com/html/html5_serversentevents.asp for more on HTML5 Server Sent Events
I have created a sample demo application which has following html page.
<!doctype html>
<!-- The DOCTYPE declaration above will set the -->
<!-- browser's rendering engine into -->
<!-- "Standards Mode". Replacing this declaration -->
<!-- with a "Quirks Mode" doctype is not supported. -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script>
function alert1(p1) {
alert("P1 is "+p1);
}
</script>
<!-- -->
<!-- Consider inlining CSS to reduce the number of requested files -->
<!-- -->
<link type="text/css" rel="stylesheet" href="Sample_JS.css">
<!-- -->
<!-- Any title is fine -->
<!-- -->
<title>Web Application Starter Project</title>
<!-- -->
<!-- This script loads your compiled module. -->
<!-- If you add any GWT meta tags, they must -->
<!-- be added before this line. -->
<!-- -->
<script type="text/javascript" language="javascript" src="sample_js/sample_js.nocache.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $window) {
$scope.nameList = [];
$scope.ShowAlert = function () {
$scope.nameList.push($scope.nameFieldContainer);
$window.alert("Hello Angular : "+$scope.nameFieldContainer);
}
});
</script>
</head>
<!-- -->
<!-- The body can have arbitrary html, or -->
<!-- you can leave the body empty if you want -->
<!-- to create a completely dynamic UI. -->
<!-- -->
<body>
<!-- OPTIONAL: include this if you want history support -->
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>
<!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
<noscript>
<div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
Your web browser must have JavaScript enabled
in order for this application to display correctly.
</div>
</noscript>
<div ng-app="MyApp" ng-controller="MyController">
<h1>Web Application Starter Project</h1>
<table align="center">
<tr>
<td colspan="2" style="font-weight:bold;">Please enter your name:</td>
</tr>
<tr>
<td data-ng-model="nameFieldContainer" id="nameFieldContainer"></td>
<td id="test" ></td>
<td id="sendButtonContainer" ng-click="ShowAlert()"></td>
</tr>
<tr>
<td> <input type ="text" data-ng-model="nameFieldContainer"> </td>
<td colspan="2" style="color:red;" id="errorLabelContainer"></td>
</tr>
<tr>
<td><input type = "button" name="click" ng-click="ShowAlert()"></td>
</tr>
</table>
<table align="center">
<tr ng-repeat = "name in nameList">
<td colspan="2" style="font-weight:bold;">{{name}}</td>
</tr>
</table>
</div>
</body>
</html>
My gwt controller class as below
package com.google.client;
import com.google.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Sample_JS implements EntryPoint {
/**
* The message displayed to the user when the server cannot be reached or
* returns an error.
*/
private static final String SERVER_ERROR = "An error occurred while "
+ "attempting to contact the server. Please check your network "
+ "connection and try again.";
/**
* Create a remote service proxy to talk to the server-side Greeting service.
*/
private final GreetingServiceAsync greetingService = GWT
.create(GreetingService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button sendButton = new Button("Add");
final TextBox nameField = new TextBox();
nameField.setText("GWT User");
final Label errorLabel = new Label();
// We can add style names to widgets
sendButton.addStyleName("sendButton");
// Add the nameField and sendButton to the RootPanel
// Use RootPanel.get() to get the entire body element
RootPanel.get("nameFieldContainer").add(nameField);
RootPanel.get("sendButtonContainer").add(sendButton);
RootPanel.get("errorLabelContainer").add(errorLabel);
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.selectAll();
// Add a handler to close the DialogBox
closeButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
sendButton.setEnabled(true);
sendButton.setFocus(true);
}
});
// Create a handler for the sendButton and nameField
class MyHandler implements ClickHandler, KeyUpHandler {
/**
* Fired when the user clicks on the sendButton.
*/
public void onClick(ClickEvent event) {
//sendNameToServer();
MyTestJS.hasPopupBlocker(nameField.getValue());
}
/**
* Fired when the user types in the nameField.
*/
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
sendNameToServer();
}
}
// Add a handler to send the name to the server
MyHandler handler = new MyHandler();
sendButton.addClickHandler(handler);
nameField.addKeyUpHandler(handler);
}
}
I am trying to call anularjs function from below native js method by using gwt button component, but i can't.
package com.google.client;
public class MyTestJS {
public static native boolean hasPopupBlocker(String name)/*-{
if (!name){
name = "Please enter name";
}else{
name = "Hello "+ name ;
}
return $wnd.ShowAlert();
}-*/;
}
How can I called angularJs ShowAlert() function from gwt (by clicking on button from java code or by other way) ?
please suggest.
any help will be appreciable......
thanks in advance.
I am tring to conditionally set the colors of data elements in a table based on their value using ng-style. Each row of data is being generated using ng repeat.
So i have something like:
<tr ng-repeat="payment in payments">
<td ng-style="set_color({{payment}})">{{payment.number}}</td>
and a function in my controller that does something like:
$scope.set_color = function (payment) {
if (payment.number > 50) {
return '{color: red}'
}
}
I have tried a couple different things. and even set the color as a data attribute in the payment object, however it seems I cant get ng-style to process data from the data bindings,
Does anyone know a way I could make this work? Thanks.
Don't use {{}}s inside an Angular expression:
<td ng-style="set_color(payment)">{{payment.number}}</td>
Return an object, not a string, from your function:
$scope.set_color = function (payment) {
if (payment.number > 50) {
return { color: "red" }
}
}
Fiddle
use this code
<td style="color:{{payment.number>50?'red':'blue'}}">{{payment.number}}</td>
or
<td ng-style="{'color':(payment.number>50?'red':'blue')}">{{payment.number}}</td>
blue color for example
It might help you!
<!DOCTYPE html>
<html>
<head>
<style>
.yelloColor {
background-color: gray;
}
.meterColor {
background-color: green;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script>
var app = angular.module('ngStyleApp', []);
app.controller('ngStyleCtrl', function($scope) {
$scope.bar = "48%";
});
</script>
</head>
<body ng-app="ngStyleApp" ng-controller="ngStyleCtrl">
<div class="yelloColor">
<div class="meterColor" ng-style="{'width':bar}">
<h4> {{bar}} DATA USED OF 100%</h4>
</div>
</div>
</body>
</html>