Angular JS CRUD update not refreshing - angularjs

My view is not getting reflected after the update/Delete/Create
My List page is EmpList. My update page is EmpDetail.
Here is my controller
$scope.UpdateEmp = function () {
var empl=$scope.Employee;
empFactory.empUpdate.update({ EmpID: $routeParams.EmpID, empval: empl });
$location.path('/EmpList');
};
Here is my Service
var resource = {
empUpdate:
$resource('../../Employee/PutEmployee/:EmpID', { EmpID: '#EmpID', empval: '#empl' }, { update: { method: 'PUT', isArray: true } })
}
return resource;
Here is my MVC controller
[HttpPut]
public JsonResult PutEmployee(int id, Employee empval)
{
empval.EmpID = id;
int index = emp.GetEmployees().FindIndex(i => i.EmpID == empval.EmpID);
emp.GetEmployees().RemoveAt(index);
emp.GetEmployees().Add(empval);
return Json(emp.GetEmployees(), JsonRequestBehavior.AllowGet);
}
MVC controller is getting called and the data is getting updated correctly, but it's not getting reflected in the main page
Note: In Emplist.html, I have the controller mapped where I m doing the query part to reflect the changes. The URL is not redirected to EmpList at all.
$scope.Employees = empFactories.query(function () {
console.log($scope.Employees);
});

You're sending the data but not using the reply:
reply = empFactory.empUpdate.update({ EmpID: $routeParams.EmpID, empval: empl });
Now you can assign the reply to your $scope

Related

How to post data on button click using AngularJS

I have an application made with .NET core framework and pure html in the front end. I was using AJAX to post and get data.
I am new to Angular and decided to convert the front end of the application to Angular for learning purposes.
For Example, I have a button that will change the state of employees from 'Billed' to 'Available' state. The ID for available state is defined in the back end and it is '1'.
//MOVE TO BENCH BUTTON CLICK
$(document).ready(function()
{
var allVals = [];
$("#MoveToBench").click(function()
{
$('input:checkbox:checked').each(function () {
allVals.push($(this).val());
});
for (i = 0;i<allVals.length;i++){
PostBenchList(allVals[i])
}
function PostBenchList(entityId) {
var data = 'entityID='.concat(entityId).concat('&nextStateId=1');
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:1783/api/Workflow?"+data,
data: data,
dataType: "text",
success: function (data) {
location.reload();
alert("Successfully added the selected Employees to TalentPool");
},
fail: function (error) {
Console.Log(error);
}
})
}
});
});
The above code is taking an array of entityID's as input. For the Angular application, the array is not required as only one entity ID will be passed.
The API controller in the backend is :
// POST api/values
[HttpPost]
public void Post(int entityId, int nextStateId)
{
JObject jsonObject = JObject.Parse(System.IO.File.ReadAllText("Config.Json"));
string jsonFile = jsonObject.GetValue("WorkfowJsonFileLocation").ToString();
var nextState = _stateServices.Get(nextStateId);
var handler = new WorkflowHandler(nextState, jsonFile, _entityServices, 1, _stateServices, _subStateServices, _appServices);
handler.PerformAction(entityId);
}
The above code worked for me and it would change the state ID of the employee(EntityID)to 1(nextStateId)
Now I have a button in AngularJS and I want it to do the same action. How would I achieve this? As I am still in the procedure of learning, I don't have a clue how to do this. Can anyone help me to achieve this? This would help me to learn and do all similar buttons.
Thank You.
You can use ng-click and call a function to post the data,
HTML:
<button ng-click="PostData()">
Click to POST
</button>
Controller:
app.controller('PostController',['$scope',function($scope)
{
$scope.sendPost = function() {
var data = $.param({
json: JSON.stringify({
name: $scope.newName
})
});
$http.post("/echo/json/", data).success(function(data, status) {
$scope.hello = data;
})
}
}]);
DEMO APP

I send http post request with angular but it does not go to the asp.net mvc action and returns html layout tags

I am doing an angular application with asp.net mvc and i made a registration form with identity, I have layout and index mvc view which i just write in it ng-view tag and i inject html pages in it, I am doing a http post request from angular controller to mvc action method but the request does not go to the mvc action, whereas when i change th views to mvc views and make a templateUrl in angular map to mvc method it works well.
Can any one help me in this problem.
[HttpPost]
[AllowAnonymous]
public async Task<JsonResult> Register(RegisterViewModel model)
{
string message = "";
if (ModelState.IsValid)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
MiddleName = model.MiddleName,
LastName = model.LastName,
UserName = model.Email,
Email = model.Email,
UserStatus = UserStatus.Waiting
};
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
message = "Success";
}
else
{
AddErrors(result);
message = "InvalidEmail";
}
}
else
{
message = "Failed!";
}
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
and this is my angular controller
MyApp.controller('RegisterController', ['$scope','$http',function ($scope, $http) {
$scope.message = '';
$scope.isFormValid = false;
//Check Form Validation
$scope.$watch('f1.$valid', function (newValue) {
$scope.isFormValid = newValue;
});
//Save Data
$scope.SaveData = function (data) {
$scope.submitted = true;
$scope.message = '';
if ($scope.isFormValid) {
$http({
method: 'POST',
url: '/Account/Register',
data: data
}).then(function (response) {
// check your response (if a success status code was resolved)
console.log(response.data);
}, function (error) {
// check your error response
console.log(error);
});
} else {
$scope.message = "Please Fill the blanks";
}
}
}]);
and this is my html page:
<div ng-controller="RegisterController">
<form name="f1" ng-submit="SaveData(user)" novalidate>
controls here
</form
1) Check your browser console for any javascript errors, if you have any, resolve them and try again!
2) Check you have the correct ActionMethodSelectorAttribute attribute ([HttpPost]) over your controller method and that your method name is spelt correctly.
3) Check that you have the correct path in your request.
4) Check you are sending the correct data to the controller!!!
5) Check that the method is public.
6) Check that you are authorised to access that controller/method.
7) Check that you don't have any duplicate method names with either, a) the same parameters and name (if your not using an ActionMethodSelectorAttribute, or b) the same names and method select attributes.
8) Remove all parameters from your method, put a breakpoint at the start of the method, and try making the request and see if it hits the breakpoint. If it works without parameters and not with, then you are not passing the correct required data into the method.
9) Make your request and check the response!! (example below):
// make your request
$http({
method: 'POST',
url: '/Controller/Method',
data: {
foo: bar
}
}).then(function(response) {
// check your response (if a success status code was resolved)
console.log(response);
}, function(error) {
// check your error response
console.log(error);
});
If you have a 404 then your method was not found, if you have a 500 then something blew up in your code, if you have a 401 then you are unauthorised etc... This is really useful to actually know what is going on with your request...
10) Check your application is running!

AngularJS application not calling the right webapi method and not displaying the right html page

Hi I am basically creating an AngularJS application that is making WebAPI calls. I have created a screen that lists all the products with help of WebApi Call. I have created a hyperlink column , when clicked should lead to details page. Whenever I click the hyperlink the original WebAPI Get method is called and not the one that should be ideally called for the details page. I am not sure what the problem is . My routing is absolutely fine. All my route states are defined properly.Below is the code.
Code in app.js. This is the file where my route states are defined.
.state("productList", {
url: "/products",
templateUrl: "/products/productListView.html",
controller: "ProductListCtrl as vm"
})
.state("productDetail", {
url: "/products/:Id",
templateUrl: "/products/productDetailView.html",
controller: "ProductDetailCtrl as vm",
resolve: {
productResource: "productResource",
product: function(productResource, $stateParams) {
var productId = $stateParams.Id;
return productResource.get({ productId: productId }).$promise;
}
}
});
The productResource.js file
(function () {
angular
.module("common.services")
.factory("productResource",
["$resource", productResource]);
function productResource($resource) {
return $resource("/api/products/:id",
{
query: {
method: 'GET',
isArray: true
}
});
}
}());
The webAPI methods in ProductController.cs file
public class ProductsController : ApiController
{
private IProductProvider _productProvider;
public ProductsController(IProductProvider productProvider)
{
this._productProvider = productProvider;
}
// GET: Porducts
public IEnumerable<Products> Get()
{
return _productProvider.GetProductData();
}
public Products Get(int id)
{
var product = _productProvider.GetProductData();
var products = product.FirstOrDefault((p) => p.Id == id);
return products;
}
}
Could somebody tell me what the problem is ? Ideally what I need is when the user clicks the hyperlink column, the productDetails state should come into force and productDetailView.html should be displayed. Also the public Products Get(int id) WebApi method should be called.
Your route parameter is defined as id:
$resource("/api/products/:id",
{
query: {
method: 'GET',
isArray: true
}
});
but you are passing an object with productId as key
productResource.get({ productId: productId })
Change the parameters object to this:
productResource.get({ id: productId })
Remember to always check your browser console for any HTTP response error if you need to debug URI related issues.

How to post or get into MVC controller?

I have a problem. I have this dropdown list :
#Html.DropDownListFor(m => m.SelectCountryId, Model.Countries, #Translator.Translate("PLEASE_SELECT"), new { id = "CountryID", #class = "form-control",ng_model="countryId", ng_change = "LoadRegions(countryId);", #required = "required" })
And i need on ng_change to get into MVC controller that looks like this:
[AllowAnonymous]
public JsonResult GetRegions(int countryId) // return a JsonResult
{
IUserManager manager = UserFactory.GetUserManager(WebConfiguration.DefaultTerminalId);
var model = manager.GetRegions(countryId);
return Json(model, JsonRequestBehavior.AllowGet);
}
This is script in angular:
$scope.LoadRegions = function (countryId)
{
console.log("COUNTRY ID: ", countryId);
$http.post('/app/Account/GetRegions/'+ countryId).then(function (response)
{
alert(response);
});
}
I get country ID but in console i get this error:
POST http://localhost:60789/app/Account/GetRegions/4 500 (Internal Server Error)
The default routing in MVC allows for {controller}/{action}/{id} but your controller is expecting {controller}/{action}/{countryId}.
You can change your call to look like:
GetRegions?countryId=XXX
Or change your method signature to look like:
public JsonResult GetRegions(int id)
Or, if you really want to, you can accommodate this route in your RouteConfig.cs
Edit: I just realized you're calling this with $http.post but everything in your code suggests you want this to be a GET, so I'd change your angular code to $http.get()
From the looks of it there are a few problems in your javascript.
Try the following.
$scope.LoadRegions = function (countryId)
{
var params = {};
params.countryId = countryId;
console.log("COUNTRY ID: ", countryId);
$http.post('/Account/GetRegions/', params).then(function (response)
{
alert(response);
});
}
As you can see you're passing in the params object with the country ID, you are making a call to the POST on the server side also -> Seperate to the angular app folder.

AngularJS factory. I need to call a method in a factory passing in a parameter then I need to retrieve the result from a different controller

I am new to AngularJS. I am building an email front-end as a college project.
I have an inbox view that retrieves emails from a json file. It works as expected by making this call: $scope.emails = InboxService.query();.
When the user clicks on an email they are redirected to a new page where I want to view the email, also from a json file (for testing only).
The controller:
app.controller('InboxController', function ($scope, $location, InboxService, EmailService) {
//Make call to email by id
$scope.viewEmail = function(emailId)
{
//DOES NOT WORK
EmailService.find({id: emailId});
$location.path('inbox/email/' + emailId);
};
//Make call to inbox
$scope.emails = InboxService.query();
});
When the user clicks on an email I want to use the id to retrieve another json file and pass it to a separate controller for a new page.
This is my EmailController:
app.controller('EmailController', function ($scope, InboxService, EmailService) {
$scope.emails = {};
//DOES NOT WORK
EmailService.getEmail(function(response){
$scope.emails.email = response;
});
});
This is the email service: DOES NOT WORK
app.factory('EmailService', function ($resource) {
var thisEmail = {};
thisEmail.find = function () {
thisEmail = $resource('json/message/:id.json', {}, {
get: {method: 'GET', params: {id: '#id'}}
})
},
thisEmail.getEmail = function () {
return thisEmail;
};
return thisEmail;
});
The service does not do what i want. I want to retrieve a json file using an id, then be able to access that file in the EmailController.
Try:
app.factory('EmailService', ['$resource',function ($resource) {
return $resource('json/message/:id.json', {}, {
get: {method: 'GET', params: {id: '#id'}}
});
}]);
In your controller:
EmailService.get({id:emailId});
You should use the built in state provider https://docs.angularjs.org/api/ngRoute/service/$route
or https://github.com/angular-ui/ui-router/wiki instead of directly working with the location hash.

Resources