Dropdownlist is not setting values using angular JS - javascript

I have a requirement where I want to bind dropdownlist using MVC and angular JS.
I tried like below
var app1 = angular.module('Assign', [])
app1.controller('SAPExecutive_R4GState', function ($scope, $http, $window) {
// alert(UMSLocationDetails);
var LocObj = JSON.parse(UMSLocationDetails)
var ZoneValue = "";
$.each(LocObj, function (index, element) {
ZoneValue += element.LocationID + ",";
});
ZoneValue = ZoneValue.substr(0, ZoneValue.length - 1);
var Values = { "MaintZones": ZoneValue };
alert(JSON.stringify(Values));
$scope.DefaultLabel = "Loading.....";
$http({
method: "POST",
url: "/App/GetR4GStates",
dataType: 'json',
data: JSON.stringify(Values),
headers: { "Content-Type": "application/json" }
}).success(function (result) {
$scope.DefaultLabel = "--Select--";
$scope.State = data;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
});
<select id="SAPExecutive_R4GState" class="form-control" ng-model="R4GState.Selected" ng-controller="SAPExecutive_R4GState as R4GState" ng-init="Select" ng-options="b for b in list">
</select>
And my CS code
[HttpPost]
public JsonResult GetR4GStates(string MaintZones)
{
List<SelectListItem> lstR4GState = new List<SelectListItem>();
try
{
Filters ObjFilter = new Filters();
DataTable dt = ObjFilter.GetR4GState(MaintZones);
if (dt.Rows.Count > 0)
{
lstR4GState = (from DataRow dr in dt.Rows
select new SelectListItem()
{
Text = Convert.ToString(dr["R4GSTATENAME"]),
Value = Convert.ToString(dr["R4GSTATECODE"])
}).ToList();
}
else
{
SelectListItem slEmptyData = new SelectListItem();
slEmptyData.Text = "No Data found";
slEmptyData.Value = "No Data found";
lstR4GState.Add(slEmptyData);
}
}
catch (Exception e)
{
}
// ErrorLog.HandleErrorLog("", "", "GetR4GStates", "Error2");
return Json(lstR4GState);
}
I am getting values in return Json(lstR4GState); but the values are not getting set in the dropdown.
Please suggest where I am going wrong as I am new to angular

It is recommended to user THEN and CATCH in AngularJS > 1.5
This should work:
angular.module('Assign', [])
.controller('SAPExecutive_R4GState', function($scope, $http, $window) {
const payload = {};
$http.get('https://dog.ceo/api/breeds/list/all', payload)
.then(function(response) {
// Please be aware RESPONSE contains the whole response.
// You probably want RESPONSE.DATA
console.log(response.data);
})
.catch(function(err) {
// do something with err message });
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="Assign" ng-controller="SAPExecutive_R4GState"></div>
Please note this example uses a GET request, just so i could show it works,
in a GET request, the payload will be added as querystring
If you change it to $http.post, the payload will be added into the body of the request.

Related

How can i use array of objects from database as filter?

// filter with data from database not working
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
// get the object array from database with name and id
dbOperations.views("getPositions", "").then(function(res) {
positions = res; // this is the desired value: [{name:"cashier",id:1},{name:"operator",id:2}]
});
var poitionName = "";
return function(positionNum) {
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
}
});
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
}).then(function success(res) {
return res;
}, function myError(response) {
// console.log("Error");
});
}
});
When I console.log the positions, it prints the data that I need. but the filter is not working. maybe because the data is from database and it is waiting to respond. dbOperations is the in the service and I use $http.
Please help me with this. Thankyou.
In the service, just return the http request instead of unwrapping the promise.
app.service('dbOperations', function($http) {
this.getAccessPosition = function() {
return $http({
method: "POST",
url: "/common/functions.php",
data: {
'process': "getAccessPosition",
'data': ""
}
})
}
});
in the filter do the service call inside the callback function.
app.filter('position', function($http, dbOperations) {
console.log(dbOperations.getAccessPosition());
var positions = []; //[{name:"cashier",id:1},{name:"operator",id:2}];
var poitionName = "";
return function(positionNum) {
dbOperations.views("getPositions", "").then(function(res) {
positions = res.data;
positions.forEach(function(p) {
if (p.id == positionNum) {
poitionName = p.name;
return false;
}
});
return poitionName;
});
}
});

ASP.NET MVC Unknown Action when delete is pressed

I have a problem, when I try to delete something, it gives me the following error message:
"Error: Unknown Action"
This is my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int? id)
{
string result = null;
try
{
if (id == null)
{
result = HIQResources.errorMessageUnknownAction;
return new JsonResult { Data = result };
}
StudentViewModel vm = new StudentViewModel();
StudentDetail studentDetail = studentManager.GetStudentDetailById(id.Value);
if (studentDetail == null)
{
result = HIQResources.errorMessageUnknownRecord;
return new JsonResult { Data = result };
}
int deleteResult = studentManager.Delete(id.Value);
if (deleteResult == 1)
{
vm.Alert.SetSuccessMessage(HIQResources.messageOperationSuccess);
TempData["alert"] = vm.Alert;
result = HIQResources.messageOperationSuccess;
return new JsonResult { Data = result };
}
else
{
vm.Alert.SetErrorMessage(HIQResources.errorMessageUnableToExecuteOperation);
TempData["alert"] = vm.Alert;
result = HIQResources.errorMessageUnableToExecuteOperation;
return new JsonResult { Data = result };
}
}
catch (DbUpdateException ex)
{
Log.AddLogRecord(LogManager.LogType.Warning, LogManager.LogPriority.Low, LogManager.LogCategory.Teacher, ex.Message, ex.StackTrace, base.GetLoggedUser());
result = HIQResources.errorMessageUnableToDeleteRecord;
return new JsonResult { Data = result };
}
catch (Exception ex)
{
Log.AddLogRecord(LogManager.LogType.Error, LogManager.LogPriority.High, LogManager.LogCategory.Inscription, ex.Message, ex.StackTrace, base.GetLoggedUser());
result = HIQResources.errorMessageExceptionOccurred;
return new JsonResult { Data = result };
}
}
This is my Javascript:
$('#ModalDeleteButton').on("click", function (e) {
var token = $('input[name="__RequestVerificationToken"]').val();
$.post("/Student/Delete/",
{
__RequestVerificationToken: token,
id: id
},
function (data) {
$('#myModal .close').click();
var baseurl = '#Url.Action("Index")';
var url = baseurl + "?message=" + data;
window.location.href = url;
});
});
I would need more specific details on this error, it seems to me that the controller and the javascript is right, so I don't really know what possibly can be.
If you're going to call $.post then you need to put the [HttpPost] attribute above the method definition. Otherwise, it just assumes that method is actually a GET (which is why the action is "unknown")
EDIT:
Try changing your $.post to this:
$.ajax({
type: "POST",
data: {
__RequestVerificationToken: token,
id: id
},
success: function(data) {
$('#myModal .close').click();
var baseurl = '#Url.Action("Index")';
var url = baseurl + "?message=" + data;
window.location.href = url;
}
});

Is there any better way to display POST request in Angular Js

I have used both PUT and POST request to modify and create a data. But the thing is POST request is not working properly. When i click on add() button , automatically POST request is generating id in the json-data before filling the information in the text fields.
Moreover data should be updated when I click on the save() button . Below I have pasted my code, if I have made any mistake tel me know and I appreciate every one whomever gives any information.
HTMl :
<button class="btn btn-info" ng-click="addmode()"> Add </button>
<button class="btn btn-success" ng-show="editMode" ng-click="saveinfo()"> Save </button>
Angular JS :
$scope.addmode = function(information) {
var postinfo = information;
$http({
url:'http://localhost:3000/contacts' ,
method : 'POST',
data : postinfo
})
.then(
function successCallback(response) {
$scope.selectedcontact = '';
console.log(response.data)
},
function errorCallback(response) {
console.log("Error : " + response.data);
});
};
First create services/api.js
angular.module('app')
.factory('api', function ($rootScope,ApiEndpoint, $http, $q,$timeout,$cookies) {
var get = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.GET};
return this.call(config);
};
var del = function (url) {
var config = {url: url, method: ApiEndpoint.Methods.DELETE};
return this.call(config);
};
var post = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.POST, data: data};
return this.call(config);
};
var put = function (url, data) {
var config = {url: url, method: ApiEndpoint.Methods.PUT, data: data};
return this.call(config);
};
return {call: call, get: get, post: post, del: del, put: put};
});
After create service/apiendpoint.js
angular.module('app')
.constant('ApiEndpoint', {
ServerUrl: 'http://localhost/',
BaseUrl: 'http://localhost/',
Methods: {GET: 'GET', POST: 'POST', PUT: 'PUT', DELETE: 'DELETE'},
Models: {
test:"fe_api/test",
},
URLS: {
QUERY: 'app/'
},
getUrl: function (url) {
var host=window.location.host;
var protocol=window.location.protocol ;
return protocol+"//"+host+"/"+url;
}
});
**Create model handler **
angular.module('app')
.factory('ApiService', function (api, ApiEndpoint) {
var getModel = function (url_part)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.get(url);
};
var getModelViaPost = function (url_part, data)
{
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + url_part;
return api.post(url, data);
};
var postModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.post(url, data);
};
var putModel = function(model_name, data) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name;
return api.put(url, data);
};
var deleteModel = function(model_name, id) {
var url = ApiEndpoint.getUrl(ApiEndpoint.URLS.QUERY) + model_name + '/' + id;
return api.delete(url);
};
return {
getModel: getModel,
postModel : postModel,
putModel : putModel,
deleteModel : deleteModel,
getModelViaPost : getModelViaPost
};
});
write API call in the controller
var data = {
wut_token: $cookies.data,
};
ApiService.postModel(ApiEndpoint.Models.test, data).then(function (response) {
if (response.SUCCESS == "FALSE") {
} else {
}
})

How to pass parameter from ActionResult to JsonResult?

How can I pass the Id parameter(I already pass in the Id parameter) from ActionResult to JsonResult? Because now I cannot pass in the Id data to JsonResult parameter, so it cannot hit the following JsonResult code.
I using angularjs to display the List of table.
[HttpGet]
public ActionResult ManageCustomerStocks(Int64 Id)
{
return View();
}
public JsonResult GetStocksByCustomerId(Int64 Id)
{
List<CustomerStocksVM> model = new List<CustomerStocksVM>();
var stocks = _repositories.GetStocksByClientProfileId(Id);
var result = from stock in stocks
select new StocksVM()
{
Code = stock.Code,
Name = stock.Name
};
model = result.ToList();
return Json(new
{
customerstocks = model
},JsonRequestBehavior.AllowGet);
}
Javascript:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.reverse = true;
$scope.sortBy = function (propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
$http({
method: 'POST',
url: 'GetStocksByCustomer'
})
.then(function (response) {
console.log(response);
$scope.customerstocks = response.data.customerstocks ;
}, function (error) {
console.log(error);
});
}]);
$http({
url: 'request-url',
method: "POST",
data: { 'id' : urId }
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
});
If you want to GET something from the backend, use http.get instead:
javascript:
function GetStocksByCustomerId(id) {
return $http.get("GetStocksByCustomer", { params: { "id":
id} })
.then(function (response) {
return response.data
})
.catch();
}
Set your http calls in an angular service

AngularJS Http Post - 500 Internal Server Error

I know there's a lot of other 500 (Internal Server Error) questions out there, but reading them is still not helping my case.
I am working on two angularjs methods that have $http post calls in them.
FIRST PROBLEM
The first successfully hits the server-side controller, and returns a JSON object as I expect it, but my drop downs are not being filled by the result of the factory call.
One thing that concerns me, is the console output. (As you'll see in the code below I have several print statements.) The URL is printed, and then my drop down options field is printed as undefined, and then the response from the server comes back with the response. Do I need to tell the JS to wait for the response? Some sort of ASYNC?
SECOND PROBLEM
I have the exact same http post method call (but with new variables), and I get the 500 (Internal Server Error) error message. The server-side ctrl method is not being hit for this call (based on break point in ctrl).
Questions
How do I fill my drop down successfully with the result of the
$http.post call?
Why is my second $http.post method creating the 500 (Internal Server Error)?
Javascript
'use strict';
var app = angular.module('LineModule', ['ngMaterial']);
app.controller("LineCtrl", ['$scope', '$http', 'LineService',
function ($scope, $http, LineService) {
$scope.Types = LineService.get_DropDownList("Type");
console.log("Types:"); console.log($scope.Types);
$scope.Statuses = LineService.get_DropDownList("Status");
$scope.FundingSources = LineService.get_DropDownList("Funding_Source");
...
$scope.get_DeptLeader = function () {
$scope.SelectedLeader = LineService.get_DeptLeader($scope.CPOC_Title, $scope.CostCenter_ID);
};
}]);
app.factory('LineService', ["$http", function ($http) {
return {
...
***FIRST METHOD***
get_DropDownList: function (field) {
var info = {
section: 'Line',
field: field
};
var URL = getBaseURL() + 'DBO/DropDown_GetList';
console.log(URL);
var DropDown;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DropDown = response.data;
console.log(DropDown);
return DropDown;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
***SECOND METHOD***
get_DeptLeader: function (CPOC_Title, CostCenter_ID) {
console.log("call get leader");
if (CPOC_Title < 1 || CPOC_Title == undefined) { return "No Title Selected"; }
if (CostCenter_ID < 1 || CostCenter_ID == undefined) { return "No Cost Center Selected"; }
console.log(CPOC_Title);
console.log(CostCenter_ID);
var info = {
Leader_ID: CPOC_Title,
CostCenter_ID: CostCenter_ID
};
var URL = getBaseURL() + 'DBO/DeptLeader_GetCurrent';
console.log(URL);
var DeptLeaders;
$http({
method: 'POST',
url: URL,
data: JSON.stringify(info),
})
.then(function (response) {
if (response !== 'undefined' && typeof (response) == 'object') {
DeptLeaders = response.data;
console.log(DeptLeaders);
return DeptLeaders;
}
else {
console.log('ERROR:');
console.log(response);
return 'No Options Found';
}
});
},
};
}]);
DBO Controller: Server-Side
[HttpPost]
public JsonResult DeptLeader_GetCurrent(string Leader_ID, string CostCenter_ID)
{
try {
List<SelectListItem> DL = DB.DeptLeader_GetByIDs(Leader_ID, CostCenter_ID);
return Json(DL, JsonRequestBehavior.AllowGet);
}
catch (Exception e){
string error = e.ToString();
return null;
}
}
[HttpPost]
public JsonResult DropDown_GetList(Sections section, DropDownFields field)
{
return Json(DB.GetDropDownValues(section, field), JsonRequestBehavior.AllowGet);
}
CSHTML
<div ng-app="LineModule" ng-controller="LineCtrl" class="container col-md-12">
...
<select ng-model="Type_ID" class="form-control" required>
<option ng-value="T.Value" ng-repeat="T in Types">{{T.Text}}</option>
</select>
...
<select ng-model="CPOC_Title" class="form-control" ng-change="get_DeptLeader()">
<option ng-value="D.Value" ng-repeat="D in DeptLeaders">{{D.Text}}</option>
</select>
{{SelectedLeader}}
...
</div>

Categories

Resources