Pushing multiple entries and saving them in database through AngularJS - angularjs

I am stuck saving multiple rows I pushed in "$scope.arr" to my SQL Server database. I have my code below and it works fine but when I click on "Save To DB" button after adding/pushing some entries by pressing "Add Person" button, it passes a row with null values to SQL Server database. Please guide me where I am doing the mistake:
I also heard about using angular.forEach loop but I am confused using that too.
I have my model class "TestModel.cs" here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
My MVC Controller named TestController's Add method here:
[HttpPost]
public string AddPerson(TestModel test)
using (TestContext db = new TestContext())
{
if (test != null)
{
db.TestModels.Add(test);
db.SaveChanges();
return "Successful";
}
else
{
return "Failed";
}
}
}
My AngularJS script here:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
$scope.addPerson = function () {
var myobj = {
FirstName: $scope.firstname,
LastName: $scope.lastname
}
$scope.arr.push(myobj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
alert(msg.data);
}, function () {
alert('Error In Adding Person');
});
};
});
app.service("TestService", function ($http) {
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
});
And my Index.cshtml file here:
<div ng-controller="TestCtrl">
<form>
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
<table class="table table-bordered">
<tr>
<th>S. No</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{$index+1}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
</tr>
</table>
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
Your help will be appreciated. Thanks!

Then server side action should expect collection of TestModel, you could us List there. If you [FromBody] before parameter, you don't need to stringify data before posting it to server.
Code
[HttpPost]
public string AddPerson([FromBody] List<TestModel> test)
using(TestContext db = new TestContext()) {
test.forEach(t=> {
if (t != null) {
db.TestModels.Add(t);
return "Successful";
} else {
return "Failed";
}
});
db.SaveChanges(); //save context at the end, when no error occurs
}
}

The problem was in my Server Side Code i.e, my C# controller, this method worked:
[HttpPost]
public void AddPerson(List<TestModel> test)
{
using (TestContext db = new TestContext())
{
foreach(var t in test)
{
if (t != null)
{
db.TestModels.Add(t);
Console.WriteLine("Success");
}
}
db.SaveChanges(); //save context at the end, when no error occurs
}
}

Related

Generated password using angular js not working

I want to make the password is auto generated and to pass it to the controller :
this is my view.jsp:
<tr>
<td class="leftDetails">Password</td>
<td class="rightDetails"><input type="text" name="password" ng-model="newUser.password" ng-disabled="isEditMode" id="p"/></td>
<td class="rightDetails"><input type='button' value ='generate' onclick='document.getElementById("p").value = Password.generate(16)' ng-show="add"></td>
<td class="leftDetails"></td>
<td class="rightDetails"></td>
</tr>
<script>
var Password = {
_pattern : /[a-zA-Z0-9_\-\+\.]/,
_getRandomByte : function()
{
if(window.crypto && window.crypto.getRandomValues)
{
var result = new Uint8Array(1);
window.crypto.getRandomValues(result);
return result[0];
}
else if(window.msCrypto && window.msCrypto.getRandomValues)
{
var result = new Uint8Array(1);
window.msCrypto.getRandomValues(result);
return result[0];
}
else
{
return Math.floor(Math.random() * 256);
}
},
generate : function(length)
{
return Array.apply(null, {'length': length})
.map(function()
{
var result;
while(true)
{
result = String.fromCharCode(this._getRandomByte());
if(this._pattern.test(result))
{
return result;
}
}
}, this)
.join('');
}
};
My problem is want to pass the generated password to my controller ,it was empty
How to correct that. thanks in advance?
The angular way to solve this issue is to update your input ng-model instead of selecting the element (Jquery way).
Instead of onClick use ng-click="newUser.password = Password.generate(16)"

Not able to display the value from Json response

I am trying to get a json web response from jersey web service using hibernate.The values are returned from database as i checked in the console.The problem is that when i try to print that in the angular like this
<h1>Welcome to Hibernate Jersey Angular CMS</h1>
<div id='err'></div>
<a href="add.html" class='btn btn-success'>New Article</a>
<p>
<div>
<table id='blogList' class="table table-bordered" ng-controller='MyController'>
<tr>
<th>Latest Articles</th>
<th>Actions</th>
</tr>
<tr ng-repeat='elem in data'>
<td>{{elem.id}}</td>
<td><a class='btn btn-warning' href="modify.html?id={{elem.id}}">Modify</a></td>
</tr>
</table>
</div>
</body>
<script src='javascripts/jquery2.1.3/jquery.min.js'></script>
<script src='javascripts/bootstrap3.3.2/js/bootstrap.min.js'></script>
<script src='javascripts/angular1.2.19/angular.js'></script>
<script src='javascripts/json/json2.js'></script>
<script>
function MyController($scope, $http) {
//$scope.data = [{title: 'welcome hello'},{title: 'great testing'}];
$http.get("webapi/blog/list", {}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
alert("error");
})
}
</script>
</html>
the value is not displayed.It is displayed blank like this
I know i am getting proper response as the number of rows min the image is same as the number of entries in the table.This is my code for hibernate
public List<Love> getAllLeaves() {
Session session = HibernateTest.getSession();
String hql = "from Love";
Query qry = session.createQuery(hql);
List<Love> list = qry.list();
Iterator i=list.iterator();
while(i.hasNext())
{
Love l=(Love) i.next();
//System.out.println("staretd");
}
session.close();
return list;
}
and the jersey code
#GET
#Path("list")
#Produces({ "application/json" })
public List<Love> list() {
List l= new LeaveDao().getAllLeaves();
Iterator i=l.iterator();
while(i.hasNext())
{
Love m=(Love)i.next();
System.out.println(m.getLove());
}
return l;
}
and bean class
package com.king.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.ws.rs.QueryParam;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
public class Love {
public Love(String Love) {
this.id = Love;
}
public Love()
{}
public String getLove() {
return id;
}
public void setLove(String Love) {
this.id = Love;
}
#Id
#QueryParam("id")
private String id;
}
added network response

How to send list inside model - AngularJS

i have a problem with my model.
I need send a list of another object to my controller, but i dont know how to create this object using AngularJS.
I have three input field, homePhone, cellphone and contact, all fields are about phone, and my ClientModel has a list of phones. What i want to do, is get this three fields and include in a list inside client model.
**MVC Model "Client"**
public int Id { get; set; }
public string Name { get; set; }
public string Email{ get; set; }
public IEnumerable<Phone> Phones { get; set; }
**MVC Model "Phone"**
public int PhoneId { get; set; }
public int ClientId { get; set; }
public int PhoneType { get; set; }
public string Number { get; set; }
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="?">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>
Controller JS
$scope.saveClient = function(client) {
clientesAPI.saveCliente(client).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});`enter code here`
}
What you could do is create actual Constructor functions in JS and consistently model you current Server Side MVC Model.
So is would look something like this ...
angular.module('app', [])
.factory('Client', function() {
return Client;
function Client() {
this.id = 0;
this.name = '';
this.email = '';
this.phones = [];
}
Client.prototype.init = function(client) {
this.id = client.id;
this.name = client.name;
this.email = client.email;
this.phones = [];
}
})
.factory('Phone', function() {
return Phone;
function Phone() {
this.phoneId = 0;
this.clientId = 0;
this.phoneType = 'Default Phone Type';
this.number = 0;
}
Phone.prototype.init = function(phone) {
this.phoneId = phone.phoneId;
this.clientId = phone.clientId;
this.phoneType = phone.phoneType;
this.number = phone.number;
}
})
.factory('clientService', function($http, $log, Client, Phone) {
var service = {
getClient: getClient,
saveClient: saveClient
};
return service;
//////////////////////////
function getClient() {
return $http.get('clientApi')
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
var clients = response.data;
angular.forEach(clients, function(client) {
client = new Client().init(client);
angular.forEach(client.phones, function(phone) {
phone = new Phone().init(phone);
})
})
return clients;
}
function error(response) {
$log.error('Error getting Clients: ' + response.data);
}
}
function saveClient(client) {
return $http.post('clientApi', client)
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
$log('Saved Client Successfully');
}
function error(response) {
$log.error('Error saving Client: ' + response.data);
}
}
})
// I would use Controller As Syntax normally
.controller('clientController', function($scope, clientService, Client, Phone) {
$scope.client = new Client();
$scope.client.phones.push(new Phone());
$scope.savedClient;
$scope.saveClient = function() {
$scope.savedClient = $scope.client;
alert('Yeah we saved some data!!');
//Unconmment this to access the real service, Nowhere to call here :-)
//clientService.saveClient($scope.client);
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="clientController">
<!-- Use ngRepeat to simplify things a bit -->
<div class="form-group col-lg-4" ng-repeat="phone in client.phones track by phone.phoneId">
<label>{{phone.phoneType}}</label>
<input class="form-control" ng-model="phone.number">
</div>
<!-- You will already have access to the updated model in you controller -->
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>
<!--Display Saved Data-->
<pre>{{savedClient | json}}</pre>
</div>
</div>
I like the idea of this approach for a couple of reasons.
You can new up a Client or a Phone in you controller and know for a fact that or expected model properties are there when Angular tries to render them. (This avoids the annoying client.phones.phoneId is not defined errors)
Your model definition is now in one spot on the JS side of the house. Even though this looks like duplication ... well it is, but you will have to define this somewhere to send it back to the server anyways. So I prefer to do it in one reusable spot.
You get and Arrays of Client and Phone when you are outputting the model properties to the Console. This just make me feel good :-)
This was a bit of an overkill for your question, but I like the clean feel of this approach to Front End Modeling.
You can create a new object for your model and add the phones property there.
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="homePhone">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="cellPhone">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="contactPhone">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>
Controller
$scope.saveClient = function() {
var phones = [
{ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
{ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
{ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
var data = {
Id: $scope.client.Id,
Name: $scope.client.Name,
Email: $scope.client.Email,
Phones: phones
};
clientesAPI.saveCliente(data).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});
};
first you need to define ng-model for your view, suppose -
<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">
Now you can make a json object and post that, then on server side you can access all the phones by for-each loop -inside your controller -
var vm = this;
var phnList = {
hphone: vm.hphone,
cellPhone: vm.cellPhone,
contactPhn: vm.contactPhone
};
Now u can post using $http service
$(http).({
url : "urULR",
data : phnList,
method :"post"
}).then(fuction(response) {
vm.message = "save success";
});

Passing data from html to Web API via Angular

I have a Web API where my repository class is:
public class myRepository
{
public myClasses.Type[] GetAllTypes()
{
return new myClasses.Type[]
{
new myClasses.Type
{
typeId="1",
typeVal = "New"
},
new myClasses.Type
{
typeId="2",
typeVal = "Old"
}
};
}
public myClasses.Employee[] GetAllEmployees()
{
return new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
}
public bool VerifyEmployeeId(string id)
{
myClasses.Employee[] emp = new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
for (var i = 0; i <= emp.Length - 1; i++)
{
if (emp[i].empId == id)
return true;
}
return false;
}
}
and here is my controller:
public class myClassesController : ApiController
{
private myRepository empRepository;
public myClassesController()
{
this.empRepository = new myRepository();
}
public myClasses.Type[] GetTypes()
{
return empRepository.GetAllTypes();
}
public myClasses.Employee[] GetEmployees()
{
return empRepository.GetAllEmployees();
}
[HttpGet]
public bool VerifyEmployee(string id)
{
return empRepository.VerifyEmployeeId(string id);
}
}
Now I have created a web application where I included angularJS. Here is my html (EmployeeLogin.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employee ID</title>
<script src="../../Scripts/jquery-2.2.0.min.js"></script>
<script src="../../Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="../../Scripts/angular.js"></script>
<script src="EmployeeLoginCtrl.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
<form ng-submit="ValidateEmployeeId()" method="get" id="frmLogin" action="">
<input ng-model="empId" type="text" id="txtEmpId" />
<br />
<input type="submit" value="Submit" id="btnSubmit" />
<br />
<span id="lblMsg">{{EmployeeValidate}}</span>
</form>
</div>
</body>
</html>
What I want to accomplish is when the user enters their ID, I want to call myController function VerifyEmployee, pass it the ID entered by the user and output message of success or failure to the web page.
I am in need of some assistance fixing up my angular controller. here is what I got so far:
(function () {
angular.module("myClassesApp", []).controller("myClassesController", myValidateFunction);
myValidateFunction.$inject("$scope", "$http");
function myValidateFunction($scope, $http) {
$scope.ValidateEmployeeId = function () {
alert($scope.empId);
$http.get('http://localhost:49358/api/myClasses/VerifyEmployee/' + $scope.empId).
then(function (result) {
alert(result);
$scope.EmployeeValidate = result.data;
});
}
};
})();
My main question is how do I pass the id from the textbox to the angular controller?
Also how I ensure my angular function is only called when the form is submitted by the user, not when the page loads initially?
Can someone please point me in the right direction in regards to getting data from Web API and displaying it on the page?
So far the page loads, immediately displays "false" in the message label. then I enter ID and click submit and then nothing happens. ow can I ensure that angular function gets called?
So, in your UI, whatever you're data-binding to (ng-model, etc..) you have access to in Angular. In your example, you have <input ng-model="empId" type="text" id="txtEmpId" /> but I don't see a $scope.empId..Where is empId coming from then?
UI
<div ng-app ng-controller="myClassesController">
<div>Enter your User ID:</div>
<input ng-model="empId"></input>
<input type="submit" ng-click="checkUser()" value="Login"></input>
</div>
Controller
function myClassesController($scope) {
$scope.empId = '';
$scope.checkUser = function () {
// hit your api with user id
alert($scope.empId);
}
}
Here's a working example for you : JSFiddle

How Exporting a table to Excel?

what is the best way of this? I have table and it's data coming from api. I used angularJs for data. Here my source codes:
Here's my table in Index:
<div style="width:1100px; max-height:480px; overflow:scroll; border-top:1px solid #808080">
<table class="table">
<tr>
<th>AdaNo</th>
<th>ParselNo</th>
<th>CiltNo</th>
<th>SayfaNo</th>
<th>ZeminTip</th>
<th>İl</th>
<th>İlçe</th>
<th>Mahalle</th>
<th>Kurum</th>
<th>Alan</th>
<th>Pay</th>
<th>Nitelik</th>
<th>EdinmeSebep</th>
<th>Ad</th>
<th>SoyAd</th>
<th>TcKimlikNo</th>
<th>HissePay</th>
<th>HissePayda</th>
</tr>
<tr data-ng-repeat="zemin in Zeminler">
<td>{{zemin.AdaNo}}</td>
<td>{{zemin.ParselNo}}</td>
<td>{{zemin.CiltNo}}</td>
<td>{{zemin.SayfaNo}}</td>
<td>{{zemin.ZeminTip.Ad}}</td>
<td>{{zemin.Il.Ad}}</td>
<td>{{zemin.Ilce.Ad}}</td>
<td>{{zemin.Mahalle.Ad}}</td>
<td>{{zemin.Kurum.Ad}}</td>
<td>{{zemin.AnaTasinmaz.Alan}}</td>
<td>{{zemin.KatMulkiyeti.ArsaPay}}/{{zemin.KatMulkiyeti.ArsaPayda}}</td>
<td>{{zemin.AnaTasinmaz.Nitelik}}</td>
<td>{{zemin.Hisseler[0].EdinmeSebep}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.Ad}}{{zemin.Hisseler[0].Kisi.TuzelKisi.Ad}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.SoyAd}}</td>
<td>{{zemin.Hisseler[0].Kisi.GercekKisi.TcKimlikNo}}</td>
<td>{{zemin.Hisseler[0].HissePay}}</td>
<td>{{zemin.Hisseler[0].HissePayda}}</td>
</tr>
</table>
</div>
Here's my Apis for this Data:
[Route("api/TapuZeminApi/GetZemins")]
[HttpPost]
public string GetZeminsFromZeminArg(object arg)
{
ZeminArg zemArg = SConvert.DeserializeJSON<ZeminArg>(arg.ToString());
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromArgs(zemArg);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
// GET api/<controller>/5
public string GetZeminsFromTcNo(long id)
{
List<TapuZeminModel> zeminList = TapuModule.GetZeminListFromTcNo(id.ToString());
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
public string GetZeminsFromKurumId(long id)
{
List<TapuZeminModel> zeminList = TapuModule.GetZeminListKurumId(id);
string jsonResult = SConvert.SerializeJSON(zeminList);
return jsonResult;
}
Article
I used it in my solution like:
First made ExportToExcelService.Js:
angular.module('TapuAppModule')
.factory('Excel', function tapuExcelFactory($window) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function (s) { return $window.btoa(unescape(encodeURIComponent(s))); },
format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
return {
tableToExcel: function (tableId, worksheetName) {
alert('Olcak olcak')
var table = $(tableId),
ctx = { worksheet: worksheetName, table: table.html() },
href = uri + base64(format(template, ctx));
return href;
}
};
})
and here my controller tapuController.js:
$scope.exportToExcel = function (tableId) {
$scope.exportHref = Excel.tableToExcel(tableId, 'sheet name');
$timeout(function () { location.href = $scope.fileData.exportHref; }, 100); // trigger download
};
and my button like this in Index:
<button class="btn btn-link" ng-click="exportToExcel('#dataTable')">
<span class="w-icon-page-excel"></span> Export to Excel
</button>
When I click button I'm getting alert that in ExportToExcelService.Js 'Olcak Olcak'. So I think it can be triggered method in ExportToExcelService.Js. Then I got this error like at console in Chrome:
TypeError: Cannot read property 'exportHref' of undefined
at tapuController.js:81
at angular.js:17682
at completeOutstandingRequest (angular.js:5387)
at angular.js:5659
Why I'm getting this error? What should I do?
Try to change the location.href value by $scope.exportHref; without fileData.
$timeout(function () { location.href = $scope.exportHref; }, 100); // trigger download
that works for me.

Resources