I am trying to create a new instance of a model from Angular with an ASP.NET backend. However I am facing validation errors saying that the fields are required.
This is what I have tried - template :
<h1>Add employee : </h1>
<form [formGroup]="form">
<label for="EmployeeName">Employee Name : </label>
<input type="text" formControlName="EmployeeName">
<label for="Department">Employee Department: </label>
<input type="text" formControlName="Department">
<label for="DateOfJoining">Date of joining : </label>
<input type="date" formControlName="DateOfJoining">
<label for="fileimage">Main image</label>
<input type="file" accept="image/*" fomrControlName="fileimage" (change)="onImageUpload($event)">
<button (click)="onSubmit()">Create Employee</button>
</form>
This is the Angular component:
ngOnInit(): void {
this.form=this.formBuilder.group({
EmployeeName:[''],
Department:[''],
DateOfJoining:[''],
fileimage:['', Validators.required]
})
}
onImageUpload(event) {
const file = event.target.files[0];
if (file) {
this.form.patchValue({fileimage:file});
this.form.get('fileimage').updateValueAndValidity();
const fileReader = new FileReader();
fileReader.onload = ()=> {
this.imageDisplay=fileReader.result;
};
fileReader.readAsDataURL(file);
}
}
onSubmit() {
const Employee : Employee = {
EmployeeName:this.form.get('EmployeeName').value,
Department:this.form.get('Department').value,
};
this.imageService.createEmployee(Employee, this.form.get('fileimage').value).subscribe(
()=>{
console.log("Employee Created")
},
()=>{
console.log("Error in Employee Creation")
}
);
}
This is the service I am working with :
createEmployee(employee:Employee, file:File):Observable<ArrayBuffer>{
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=<calculated when request is sent>');
const options = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data;boundary=<calculated when request is sent>'
}),
body: {}
}
return this.http.post<ArrayBuffer>(`${this.apiURLEmployee}`, {employee, file}, options)
}
And finally this is my backend endpoint :
public IActionResult Post([FromForm]Employee emp, IFormFile file)
{
MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));
int LastEmployeeId = dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").AsQueryable().Count();
emp.EmployeeId = LastEmployeeId + 1;
string wwwRootPath = _hostEnvironment.WebRootPath;
if (file != null)
{
string filename = Guid.NewGuid().ToString();
var uploads = Path.Combine(wwwRootPath, #"images\employee");
var extension = Path.GetExtension(file.FileName);
Uri domain = new Uri(Request.GetDisplayUrl());
if (emp.PhotoFileName != null)
{
var oldImagePath = Path.Combine(wwwRootPath, emp.PhotoFileName.TrimStart('/'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using (var fileStreams = new FileStream(Path.Combine(uploads, filename + extension), FileMode.Create))
{
file.CopyTo(fileStreams);
}
emp.PhotoFileName = domain.Scheme + "://" + domain.Host + (domain.IsDefaultPort ? "" : ":" + domain.Port) + "/images/employee/" + filename + extension;
}
dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").InsertOne(emp);
return Json("Employee added successfully");
}
The validation errors are from the backend. Here is the error :
Error Image
Request
Payload
Related
This the text from where im getting the error. The the code is located after function sendData(). Where it starts with the:
var file = this.files[0];
I want to make where a button sends the files to the storage and not when it detects the state has been changed
var database = firebase.database();
var uploader = document.getElementById("uploader");
var fileButton = document.getElementById("fileButton").value;
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
var d = new Date();
var month = d.getMonth();
var day = d.getDay();
var hour = d.getHours();
var minute = d.getMinutes();
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
var currentUser = document.getElementById('currentUser').href = "#";
var currentUser = document.getElementById('currentUser').innerHTML = "Cuenta";
} else {
var currentUser = document.getElementById('currentUser').href = "/auth/login.html";
var currentUser = document.getElementById('currentUser').innerHTML = "Inicio De Sesión";
window.location.href = "/auth/login.html";
}
});
function sendData() {
var file = this.files[0];
var storage = firebase.storage().ref("News/" + file.name);
var task = storage.put(file);
task.on('state_changed', function(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
}, function error(err) {
console.log("Error: " + err);
alert("Error");
}, function() {
firebase.storage().ref("News/").child(file.name).getDownloadURL().then(function(url) {
var title = document.getElementById("title").value;
var description = document.getElementById("description").value;
var ref = database.ref("News");
var data = {
imageURL: url,
Title: title,
Description: description,
Date: month + "/" + day + " " + h + ":" + minutes
}
ref.push(data);
});
});
};
HTML: Code
<div class="mainContainer">
<h1>Database</h1>
<input id="title" placeholder="Título" type="text">
<textarea id="description" placeholder="Description"></textarea>
<br>
<progress id="uploader" value="0" max="100">
0%
</progress>
<br>
<input type="file" value="upload" id="fileButton" accept=".png, .mp4, .mp3, .pdf">
<button onclick="sendData()">Enviar</button>
</div>
Probably this.files is undefined and you are trying to access the element at index 0.
I have developed an application, and in this application I want to import file Excel to multiple table in my DB, and since i am a beginner in angularJS and .NET, I work with .net web api and angularjs, and I develop a function, it works when I import the data into a singe table, but the problem how to import the data into 3 table in DB !!! . and the 3 tables are linked to each other (in my exemple code there 2 table Candidature and Candidat). My question is: how to import Excel file to multiple table in DB and thank's. ( i work with asp.net web API and angularJS )
controller.cs:
/////
[Route("api/Candidature/SaveData")]
[HttpPost]
[ResponseType(typeof(Candidat))]
public IHttpActionResult SaveData(List<Candidature> Candidatures, List<Candidat> candidat)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (var data in Candidatures)
{
db.Candidature.Add(data);
}
db.SaveChanges();
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
db.SaveChanges();
return StatusCode(HttpStatusCode.OK);
////
service.js:
SaveData: {
method: 'POST' ,
url: serviceBase + 'Candidature/SaveData',
isArray: true,
headers: {
'Content-Type' : 'application/json'
}
},
CandidatureCtrl.js :
$scope.Importation = function (data) {
$scope.SelectedFileForUpload = null;
$scope.UploadFile = function (files) {
$scope.$apply(function () { //I have used $scope.$apply because I will call this function from File input type control which is not supported 2 way binding
$scope.Message = "";
$scope.SelectedFileForUpload = files[0];
})
};
//Parse Excel Data
$scope.ParseExcelDataAndSave = function () {
var file = $scope.SelectedFileForUpload;
if (file) {
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
//XLSX from js-xlsx library , which I will add in page view page
var workbook = XLSX.read(e.target.result, { type: 'binary', cellDates:true, cellStyles:true });
var sheetName = workbook.SheetNames[0];
var excelData = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
if (excelData.length > 0) {
//Save data
Candidature.SaveData(excelData).then(function (data) {
if (data.status) {
$scope.Message = excelData.length + " record inserted";
}
else {
$scope.Message = "Failed";
}
}, function (error) {
$scope.Message = "Error";
});
// Candidature.SaveDatacandidature(excelData).then(function (data) {
// if (data.status) {
// $scope.Message = excelData.length + " record inserted";
// }
// else {
// $scope.Message = "Failed";
// }
// }, function (error) {
// $scope.Message = "Error";
// });
// $scope.SaveData(excelData);
}
else {
$scope.Message = "No data found";
}
}
reader.onerror = function (ex) {
console.log(ex);
}
reader.readAsBinaryString(file);
}
};
var dialogOpts = {
backdrop: 'static',
keyboard: false,
scope: $scope,
size: 'lg',
templateUrl: 'views/candidature/Importation.html',
controller: ['$scope', '$uibModalInstance','$sce',
function ($scope, $uibModalInstance, $sce) {
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
}
]
};
$uibModal.open(dialogOpts);
};
Importation.html :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.1/xlsx.full.min.js"></script>
<script src="http://oss.sheetjs.com/js-xlsx/jszip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>
<!--<script src="app/views/candidature/candidatureCtrl.js"></script>-->
</head>
<body ng-app="agu">
<div ng-controller="candidatureCtrl" class="container" style="margin-top:50px;">
<div class="form-inline">
<input type="file" name="file" class="form-control"
onchange="angular.element(this).scope().UploadFile(this.files)"/>
<input type="button" value="Import" class="btn btn-success" ng-disabled="!SelectedFileForUpload"
ng-click="ParseExcelDataAndSave()" />
<br/>
<span style="color:red">
{{Message}}
</span>
</div>
</div>
</body>
</html>
In your web api, you are expecting two arrays for Candidatures and candidat.
But from your controller you are passing only one array of data excelData.
So when it comes to api it doesn't execute this code,
foreach (var data in candidat)
{
db.Candidat.Add(data);
}
Because candidat is either null or undefined. So it can't go through the loop which the below code is never executed.
db.Candidat.Add(data);
First i have now tried every page in here but nothing help. So this looks like all the others bus it isn't
i simply wants a file uploader where the image's are saved first and pass the image's ID back to a hidden input field as a string so i can find images again when the form is submitted.
no matter what i do i can't prevent the page for refreshing, which make the input field disappear :(
here is my code
HTML
<label for="file-uploader" class="custom-file-upload">
<i class="fa fa-cloud-upload fa-5x"></i><br /> Custom Upload
</label>
<input style="display: none" id="file-uploader" name="file" multiple="" type="file" />
<div id="input-wrapper">
Here comes all input fields
</div>
AJAX/JSON
$("#file-uploader").change(function () {
var formData = new FormData();
var totalFiles = document.getElementById("file-uploader").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("file-uploader").files[i];
formData.append("file-uploader", file);
}
$.ajax({
type: "POST",
url: '#Url.Action("Fileuploader", "Admin")',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data, e) {
$('#input-wrapper').append($('<input>').attr('type', 'hidden').attr('name', 'imagesId').attr('value', data.Id));
},
error: function(error) {
alert("error");
}
});
return false;
});
CONTROLLER
public JsonResult Fileuploader(int? pictureId)
{
db = new ApplicationDbContext();
var name = "";
if (pictureId != null)
{
var findImage = db.Imageses.Find(pictureId);
if (findImage == null) return Json(new { result = "Error" }, JsonRequestBehavior.AllowGet);
var filename = findImage.Url.Substring(10);
var path = Server.MapPath("~/Uploads/" + filename);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
db.Imageses.Remove(findImage);
db.SaveChanges();
}
if (Request.Files.Count > 0)
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
name = Guid.NewGuid().ToString();
var fileformat = Path.GetExtension(file.FileName);
var filename = name + fileformat;
var path = Path.Combine(Server.MapPath("~/Uploads/"), filename);
file.SaveAs(path);
}
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
var img = new Images()
{
Filename = file.FileName,
DateCreated = DateTime.Now,
Url = "~/Uploads/" + name
};
db.Imageses.Add(img);
db.SaveChanges();
}
}
return Json(new { result = "Sucess", Id=name }, JsonRequestBehavior.AllowGet);
}
Is your #file-uploader sitting inside a form with an action method on it?
I would try taking the action attribute off, then adding the attribute to the form element in the success function of your ajax call.
I just disabled "enable Browser Sync" and it is working.
I am trying to make a trivial call to a SQL Server 2000 database using Angular's $http service. Angular factory containing the $http:
var RegistrationFactory = function ($http, $q, SessionService) {
return function (email, password, confirmPassword) {
var result = $q.defer();
$http({
method: 'POST',
url: SessionService.apiUrl + '/api/Account/Register',
data: { Email: email, Password: password, ConfirmPassword: confirmPassword },
headers: { 'Content-Type': 'application/json' }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
RegistrationFactory.$inject = ['$http', '$q', 'SessionService'];
And inside the AccountController:
[HttpPost]
[AllowAnonymous]
public async Task<bool> Register(RegisterViewModel model)
{
string queryString = "INSERT INTO Northwind VALUES('test', 'values')";
SqlConnection cnxn = new SqlConnection(WebConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(queryString, cnxn);
cnxn.Open();
command.ExecuteNonQuery();
cnxn.Close();
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return false;
}
await SignInManager.SignInAsync(user, false, false);
return true;
}
This program is merely trying to show that the SQL-related codes are executed upon the RegistrationFactory being utilized.
The Register.cshtml view:
<form ng-submit="register()">
<label for="emailAddress">Email Address:</label>
<input id="emailAddress" type="text" ng-model="registerForm.emailAddress" required />
<label for="password">Password:</label>
<input id="password" type="password" ng-model="registerForm.password" required />
<label for="confirmPassword">Password:</label>
<input id="confirmPassword" type="password" ng-model="registerForm.confirmPassword" required />
<button type="submit">Register</button>
</form>
And the RegisterController.js that handles above view:
var RegisterController = function ($scope) {
$scope.registerForm = {
emailAddress: '',
password: '',
confirmPassword: '',
registrationFailure: false
};
$scope.register = function () {
var result = RegistrationFactory($scope.registerForm.emailAddress, $scope.registerForm.password, $scope.registerForm.confirmPassword);
result.then(function (result) {
if (result.success) {
$location.path('/routeOne');
} else {
$scope.registerForm.registrationFailure = true;
}
});
}
}
RegisterController.$inject = ['$scope', '$location', 'RegistrationFactory'];
I am trying to figure out how to actually execute the statement as the result of my $http. Additionally, being able to pass data through the 'POST' would be awesome. And, yes, it has to be for SQL Server 2000, so Entity Framework is not an option. Thanks, everyone!
Hi I am trying to integrate worldpay on my asp.net website.
I have used this code to achieve the integration.
//test environment url
string url = "https://secure-test.worldpay.com/wcc/purchase";
//get all form elements
NameValueCollection formData = new NameValueCollection();
formData["testMode"] = "100";
//all the form fields here
//make the call to submit form data
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
inputdiv.Visible = false;
outputdiv.Visible = true;
outputdiv.InnerHtml = response;
Basically I am getting the response and displaying it on a div. Everything works, but the links are having relative path which shouldn't be the case. Except the image urls, all other urls should point to worldpay. how to achieve this?
Any suggestion will be much appreciated.
Please try this, hope this would help a lot.
Html
<form action="/complete" id="paymentForm" method="post">
<span id="paymentErrors"></span>
<div class="form-row">
<label>Name on Card</label>
<input data-worldpay="name" name="name" type="text" />
</div>
<div class="form-row">
<label>Card Number</label>
<input data-worldpay="number" size="20" type="text" />
</div>
<div class="form-row">
<label>CVC</label>
<input data-worldpay="cvc" size="4" type="text" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input data-worldpay="exp-month" size="2" type="text" />
<label> / </label>
<input data-worldpay="exp-year" size="4" type="text" />
</div>
<input type="submit" value="Place Order" />
</form>
SCRIPT
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type="text/javascript">
var form = document.getElementById('paymentForm');
Worldpay.useOwnForm({
'clientKey': 'Your_Client_Key',
'form': form,
'reusable': false,
'callback': function (status, response) {
document.getElementById('paymentErrors').innerHTML = '';
if (response.error) {
Worldpay.handleError(form, document.getElementById('paymentErrors'), response.error);
} else {
var token = response.token;
Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
console.log(token);
$.ajax({
url: "/Home/payment/",
data: { token: token },
success: function (data) {
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
//Error Message
}
});
form.submit();
}
}
});
</script>
Serve Side Code C#
public ActionResult payment(string token)
{
var restClient = new WorldpayRestClient("https://api.worldpay.com/v1", "Your_Service_Key");
var orderRequest = new OrderRequest()
{
token = token,
amount = 500,
currencyCode = CurrencyCode.GBP.ToString(),
name = "test name",
orderDescription = "Order description",
customerOrderCode = "Order code"
};
var address = new Address()
{
address1 = "123 House Road",
address2 = "A village",
city = "London",
countryCode = CountryCode.GB,
postalCode = "EC1 1AA"
};
orderRequest.billingAddress = address;
try
{
OrderResponse orderResponse = restClient.GetOrderService().Create(orderRequest);
Console.WriteLine("Order code: " + orderResponse.orderCode);
}
catch (WorldpayException e)
{
Console.WriteLine("Error code:" + e.apiError.customCode);
Console.WriteLine("Error description: " + e.apiError.description);
Console.WriteLine("Error message: " + e.apiError.message);
}
return Json(null, JsonRequestBehavior.AllowGet);
}