I want to consume web api using AngularJs to create a dashboard with c# . I succeed to consume the web api but when I want to add angular Js to create my Dashboard nothing appears. I can't figure out what is the problem.
script.js
var app = angular.module("DemandeApp", []); app.controller("DemCreditController", function ($scope, $http) {
$http.get("http://localhost:2573/api/demandes")
.then(function (response) {
$scope.labels = [];
$scope.data = [];
angular.forEach(response.data, function (value, key) {
$scope.labels[key] = value.libelle;
$scope.data[key] = value.quantite;
}
);
});
});
index.html :
<body ng-app="DemandeApp">
<div ng-controller="DemCreditController">
<canvas id="pie" class="chart chart-pie"
chart-data="data" chart-labels="labels" ></canvas>
</div></body>
You can try like the below code to push the data to your array,
$http.get("http://localhost:2573/api/demandes")
.then(function (response) {
$scope.labels = [];
$scope.data = [];
angular.forEach(response.data, function (value, key) {
$scope.labels.push(value.libelle);
$scope.data.push(value.quantite);
}
);
Related
I am trying to fetch records via ajax and displaying using AngularJS.
But my code even not invoking controller action.
I am trying this code..
<div ng-controller="MyCtrl">
<div ng-repeat="result in products">
{{result.ProductName}}
</div>
</div>
Ajax :
function MyCtrl($scope) {
$.ajax({
url: "/Products/Get/",
type: "POST",
success: function (data) {
// Success message
var myApp = angular.module('myApp', []);
$scope.products = data;
},
error: function () {
// Fail message
},
});
}
I am using this post to make it work.
Your approach is wrong.
You should use angularJS's controller directive to invoke services to consume json data.
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('MyCtrl', function ($scope, $http) {
$http.get('/Products/Get/').success(function (data) {
$scope.products = data;
});
});
</script>
I had written an article few days ago on the same.
You can go through here. This might be helpful.
you need declare module name in angularjs , and dont forget to add module name in you body or html tag..like this <body data-ng-app="app"> and then Try like this :
<script>
var app = angular.module('app',[]);
app.controller('MyCtrl',function($scope,$http){
bindData();
function bindData(
// it will be nice, if this code your separate to file service...
$http.get('/Products/Get').success(function (callBack) {
$scope.products = callBack.data;
});
);
});
</script>
and Best Implementation like This :
// in controller, injected you service name like this..
app.controller('MyCtrl',function($scope,$http ,myServices){
bindData();
function bindData(
var promiseGet = myServices.GetAll();
promiseGet.then(function(callBack){ // success
$scope.products = callBack.data;
}
,function(error){ // error
console.log(error);
});
);
});
app.service('myServices',function($http){
var vm = this;
vm.GetAll = function(){
return $http.get('/Products/Get');
}
});
and type not POST, if you want to Get data in ajax function..
i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically.
this is the code that i wrote in the view and i have a compilation error in that line at runtime:
#Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"})
"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .
public ViewResult FilterdIndex(int id)
{
var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
select new
{
BG.GROUP_ID,BG.GROUP_NAME,
Checked=(BG.GROUP_ID==id)
};
ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
return View(donor.ToList());
}
this is javascript code it executes the controller function correctly but i don't know why after returning to the view i have the error msg in this line :
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
and this is the whole function:
<script src="~/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.7.1.js" type="text/javascript"></script>
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
if ($("#DONOR_BLOOD_GROUPE_ID").val() != "Select") {
var DONOR_BLOOD_GROUPE = {};
DONOR_BLOOD_GROUPE.url = '#Url.Action("FilterdIndex", "DONOR")';
DONOR_BLOOD_GROUPE.type = "POST";
DONOR_BLOOD_GROUPE.data = JSON.stringify({ id: $("#DONOR_BLOOD_GROUPE_ID").val() });
DONOR_BLOOD_GROUPE.datatype = "html";
DONOR_BLOOD_GROUPE.contentType = "application/json";
DONOR_BLOOD_GROUPE.error = function () { alert("Error in Getting States!!"); };
$.ajax(DONOR_BLOOD_GROUPE);
}
});
});
</script>
and this is the line that causes the exception in "DONOR[dynamic]" file
<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>
I assume you come from a WebForms background where this sort of thing happens all the time with 'Events' this sadly is not how MVC works.
To do what you are trying to do, you will need to create a jquery method for the onchange event of that drop down, then do an async post to your controller.
Have a look at this tutorial which should point you in the right direction
http://www.c-sharpcorner.com/UploadFile/4b0136/working-with-dropdownlist-in-mvc-5/
Hi Asmaa Rashad you can try using this way and your action Method which you are calling using Ajax must be of type JsonResult.
<script type="text/javascript">
$(document).ready(function () {
$("#DONOR_BLOOD_GROUPE_ID").change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("FilterdIndex", "DONOR")',
dataType: 'json',
data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
success: function (data) {
},
error: function (ex) {
alert('Failed to retrieve + ex);
}
});
return false;
})
});
</script>
For reference you can check this blog creating-simple-cascading-dropdownlist-in-mvc-4-using-razor
I have built a MVC application to insert form data into DB. I used angularjs library with html5 & bootstrap.
Below is the some major lines in HTML.
form tag:
<form ng-app='MyData' ng-controller='DataController'>
Button ():
<input type="button" value="Submit" ng-click="addUser();" id="btnSubmitAddUsr" class="btn btn-success" />
Below is the ajax call using Jquery & angular js:
var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
$scope.addUser = function () {
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($scope.usrFName, $scope.usrEmail, $scope.usrPhone, $scope.selectApp.id, $scope.usrRole),
url: '/Home/AddUser',
success: function (data, status) {
$scope.clear();
},
error: function (status) { }
});
};
});
C# method:
[HttpPost]
public JsonResult AddUser(string usrFName, string usrEmail, string usrPhone, string usrApp, string usrRole)
{
var db = new SchedulerEntities();
db.Users.Add(new User { Name = usrFName, Password = "testPwd", Email = usrEmail, Phone = usrPhone, ApplicationId = Convert.ToInt32(usrApp), RoleId = Convert.ToInt32(usrRole) });
db.SaveChanges();
return null;
}
The above C# methods gets called; but the parameters shows null. Also when I check the $scope variables from browser; the form values shows correct there.
Please suggest.
You generally don't want to use $scope as your model and instead create an object for your model on the scope...you'll run into some other issues with prototype inheritance the way you are currently doing it. When you use ng-model, you should always have a '.' in the expression.
You should also use $http instead of $.ajax (it'll handle the serialization for you and run a digest cycle when the call completes).
var myData = angular.module('MyData', []);
myData.controller("DataController", function ($scope, $http) {
$scope.form = {usrFName: '', usrEmail: '', usrApp: ''}; // initialize any other form variables
$scope.addUser = function () {
$http.post('/Home/AddUser', $scope.form)
.success(function(){$scope.clear();});
};
});
I am trying to download an image
Client HTML code:
$.ajax({
url: 'http://localhost:17308/api/DownloadFile/10272',
type: 'GET',
dataType: 'json',
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
console.log('Error in Database');
}
});
This code above call the Web API just fine, but I get hit with the error --> console.log('Error in Database'); (per my console.log on error:
Web Api
Signature
public HttpResponseMessage DownloadFile(long id)
returning code:
result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue(mime);
return result;
Do I need to change my dataType from json to something else ( i assume so)
What other ways to troubleshoot this?
UPDATE
I was trying this code for returning a jpeg it makes it to success, but never displays the image.
HTML:
<button type="button" id="Download" class="btn btn-primary">Download</button>
<img id="test" alt="test" src="" />
Javascript:
var request = function () {
var ajaxOptions = {};
ajaxOptions.cache = false;
ajaxOptions.url = "/api/DownloadFile/10272";
ajaxOptions.type = "GET";
ajaxOptions.headers = {};
ajaxOptions.headers.Accept = "application/octet-stream"
ajaxOptions.success = function (result) {
console.log("start");
$("#test").attr("src", "data:image/jpg;base64," + result);
console.log("end");
};
ajaxOptions.error = function (jqXHR) {
console.log("found error");
console.log(jqXHR);
};
$.ajax(ajaxOptions);
}
$(function () {
$('#Download').on('click', request);
})
UPDATE 2:
Changed to this code and it now works
public IHttpActionResult DownloadFile(long id)
{
//code
myBytes = File.ReadAllBytes(path);
return Ok(myBytes);
}
I had the same problem until I changed the Accept header to "application/octet" and left the datatype blank. The jquery object being returned had a status of 200 and returned the data but always executed the error option. I have seen this before with the jquery datatype or Accept header did not match up with what was being returned by the Web API controller. The jqXHR object in the error response actually shows that some error was triggered but I have as of yet not found what jquery option or Web API response is causing the behavior.
<button id="submit" class="btn btn-primary">submit</button>
<img id="test" alt="test" src="" />
JavaScript
var request = function () {
var ajaxOptions = {};
ajaxOptions.cache = false;
ajaxOptions.url = "/api/question3api";
ajaxOptions.type = "GET";
ajaxOptions.headers = {};
ajaxOptions.headers.Accept = "application/octet-stream"
ajaxOptions.success = function (result) {
console.log(result);
$("#test").attr("src", "data:image/png;base64," + result);
};
ajaxOptions.error = function (jqXHR) {
console.log("found error");
console.log(jqXHR);
};
$.ajax(ajaxOptions);
}
$(function () {
$('#submit').on('click', request);
})
Api Controller
public class question3apiController : ApiController
{
public IHttpActionResult GetFile()
{
string FilePath = HttpContext.Current.Server.MapPath("~/images/images.png");
byte [] myBytes = File.ReadAllBytes(FilePath);
return Ok(myBytes);
}
}
edited: Actually after reading the following the result makes sense. If the dataType of the request is set to expect JSON but some other format is returned the error event occurs.
Ajax request returns 200 OK, but an error event is fired instead of success
I need to pass an id and get the related questions.
Error message - POST http://localhost:51949/API.asmx/GetAllQuestions/0 - 500 (Internal Server Error)
The web service works fine as I have checked in other part of C# code. Now, trying to access it from angularjs. Is this the right way?
app.js:
var app = angular.module('virtualApp', []);
controller.js:
app.controller("virtualController", function ($scope, DataFactory) {
$scope.categories=[];
$scope.GetAllQuestions = function (categoryId) {
DataFactory.GetAllQuestions(categoryId)
.success(function (data) {
$scope.categories = data;
})
.error(function (error) {
alert(error.message);
});
}
$scope.GetAllQuestions(0); //to fire at page load
});
services.js:
EDIT
app.factory("DataFactory",function ($http) {
var urlBase = "http://localhost:51949/API.asmx/";
var dataFactory = {};
dataFactory.GetAllQuestionCategories = function (categoryId) {
return $http.post(urlBase + "GetAllQuestions", { categoryId: categoryId })
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
return dataFactory;
});
I think problem with you code is you are passing id as part of url instead of it pass id in data of ajax request
Dont pass data in url like as below
//do not attach categoryId
urlBase + "GetAllQuestions/" + categoryId
instead of it pass data in data parameter of request like as below code
data: { test: 'test' }
and url will be urlBase + "GetAllQuestions
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' },
}
$http(req).success(function(){...}).error(function(){...});
one more thing you are calling function to get data than make use of Get method instead of Post method.