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..
Related
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);
}
);
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();});
};
});
This is driving me crazy. All I'm trying to do is to pass in a Id to a ActionMethod which is working and have an Object be returned to the javascript. Then in javascript, I want to be able to say something like..Objec.Property, ie/ Student.Name, or Student.GPA.
Any help is appreciated. I tried json but couldn't get that to work either.
ActionResult:
[AcceptVerbs(HttpVerbs.Get)]
public Epic GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id));
return Epictemplist.SingleOrDefault();
}
javascript:
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result);
});
});
});
</script>
result.Name is obviously wrong I just dont know how to call this the right way.
Tman, I had a similiar issue that Darin helped me with. I needed to add a $.param to my getJSON. Check out this post MVC ListBox not passing data to Action
try changing your method like this
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetEpicPropertyDetails(int id)
{
var Epictemplist = epicRepository.Select().Where(x => x.Id.Equals(id)).SingleOrDefault();
return Json(Epictemplist, JsonRequestBehavior.AllowGet);
}
Than from your JS
<script type="text/javascript">
$(document).ready(function () {
$(".ListBoxClass").click(function (event) {
var selectedid = $(this).find("option:selected").val();
event.preventDefault();
$.get("/Estimate/GetEpicPropertyDetails", { id: selectedid }, function (result) {
$(".TimeClass").val(result.Name);
}, 'json');
});
});
</script>
I'm trying to execute my controller from javascript using jquery... here is my jquery code that is executing..
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
var obj = msg.deserialize();
alert(msg);
}
});
});
</script>
Now it does execute my action..
Here is a sample of my controller class it is executing..
[AcceptVerbs(HttpVerbs.Post)]
[Url("Account/LogOn")]
public virtual ActionResult LogOn(string Username, string Password) {
if (Username == "test") {
return Json(new {
Success = true
});
} else {
return Json(new {
Success = false
});
}
}
Problem is.. when I run the method.. it just tries to download a "Logon" file which contains the result.. how do I put it back to an object in jquery so i can handle it the correct way, I've tried adding the success tag and attempt to check the msg but it doesnt even run it
Put your script inside document.ready before attempting to register any event handlers as the DOM might have not loaded yet:
<script type="text/javascript">
$(function() {
// ... copy - paste your script here
});
</script>
Also you don't need to set the dataType, jQuery knows it from the Content-Type response header from the server. Another remark: the msg object passed to the success handler is already a JSON object: you don't need to parse/deserialize it:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(msg) {
alert(msg.Success);
}
});
return false;
}
});
</script>
And the solution I would recommend you is to use the jquery.form plugin. Thanks to it your js code will look as easy as:
<script type="text/javascript">
$(function() {
$('form').ajaxForm(function(msg) {
alert(msg.Success);
});
});
</script>
Very neat stuff. You don't need to bother about serializing/deserializing data, preventing default events, it can even handle file uploads.
HIDDENHANCEMENT
var obj = msg.deserialize();
If that is not a joke, you would have spotted a hidden feature :)
If you're using jQuery v.1.4.x you don't need to parse a JSON string manually.
Using an older version, try
var obj = window.JSON.parse(msg);