I am programing a CRUD application. The add and edit do not want to work properly. For Adding, it shows me the successful message that the row is added, but nothing added in reality in my database. For Edit, I have a NullReferenceException after he tries to find the reclamation by his id :
StackTrace
In Debug mode, I can see that ng-model is doing his job, the add or edit modifications are take in account.
Here is my code :
reclamations-controller.js :
(function () {
'use strict';
angular
.module('app')
.controller('ReclamationsController', function ($scope, $http) {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = "";
$scope.Reclamations.RecDescription = "";
$scope.Reclamations.RecStatus = "";
$scope.Reclamations.RecResponsible = "";
$scope.Reclamations.RecComment = "";
// Popup variables
$scope.showModal = false;
$scope.buttonClicked = "";
$scope.toggleModal = function (btnClicked) {
$scope.buttonClicked = btnClicked;
$scope.showModal = !$scope.showModal;
};
// Export Data to Excel file
$scope.Export = function () {
$("#tblReclamations").table2excel({
filename: "Reclamations.xls",
exportOptions: {
columns: [1, 2]
}
});
}
$scope.showAddAndEditModal = false;
$scope.showAddAndEditModalFunction = function () {
if ($scope.showAddAndEditModal == false) {
$scope.showAddAndEditModal = true;
}
else {
$scope.showAddAndEditModal = false;
}
};
$scope.showImportModal = false;
$scope.showImportModalFunction = function () {
if ($scope.showImportModal == false) {
$scope.showImportModal = true;
}
else {
$scope.showImportModal = false;
}
};
// Add new reclamation function
$scope.InsertData = function () {
var Action = document.getElementById("btnSave").getAttribute("value");
if (Action == "Submit") {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$http({
method: "post",
url: "/Data/Insert_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
})
} else {
$scope.Reclamations = [];
$scope.Reclamations.RecTitle = $scope.RecTitle;
$scope.Reclamations.RecDescription = $scope.RecDescription;
$scope.Reclamations.RecStatus = $scope.RecStatus;
$scope.Reclamations.RecResponsible = $scope.RecResponsible;
$scope.Reclamations.RecComment = $scope.RecComment;
$scope.Reclamations.RecId = document.getElementById("RecID_").value;
$http({
method: "post",
url: "/Data/Update_Reclamation",
datatype: "json",
data: JSON.stringify($scope.Reclamations)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
$scope.RecTitle = "";
$scope.RecDescription = "";
$scope.RecStatus = "";
$scope.RecResponsible = "";
$scope.RecComment = "";
document.getElementById("btnSave").setAttribute("value", "Submit");
document.getElementById("btnSave").style.backgroundColor = "cornflowerblue";
document.getElementById("spn").innerHTML = "Add New Reclamation";
})
}
};
// Get all reclamations function
$scope.GetAllData = function () {
$http({
method: "get",
url: "/Data/Get_AllReclamation"
}).then(function (response) {
$scope.Reclamations = response.data;
}, function () {
alert("Error Occur");
})
};
// Delete function
$scope.DeleteReclamation = function (Rec) {
$http({
method: "POST",
url: "/Data/Delete_Reclamation",
datatype: "JSON",
data: JSON.stringify(Rec)
}).then(function (response) {
alert(response.data);
$scope.GetAllData();
})
};
// Update function
$scope.UpdateReclamation = function (Rec) {
document.getElementById("RecID_").value = Rec.RecId;
$scope.RecDate = new Date(Rec.RecDate);
$scope.RecTitle = Rec.RecTitle;
$scope.RecDescription = Rec.RecDescription;
$scope.RecStatus = Rec.RecStatus;
$scope.RecResponsible = Rec.RecResponsible;
$scope.RecComment = Rec.RecComment;
document.getElementById("btnSave").setAttribute("value", "Update");
document.getElementById("btnSave").style.backgroundColor = "Yellow";
document.getElementById("spn").innerHTML = "Update Reclamation Information";
};
});
})();
index.cshtml :
<p class="text-info text-center"><h3>Reclamations list</h3></p>
<div ng-app="app">
<div ng-controller="ReclamationsController" ng-init="GetAllData()" class="divList">
#*Reclamation Menu options*#
<div id="container" class="container">
<div class="row">
<input type="text" ng-model="searchFilter" placeholder="Search" />
<button ng-click="showAddAndEditModalFunction()" class="btn btn-primary a-btn-slide-
text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Add</strong></span>
</button>
<button class="btn btn-primary a-btn-slide-text" onclick="history.go(0);">
<span class="glyphicon glyphicon-refresh" aria-hidden="true"></span>
<span>
<strong>Refresh</strong>
</span>
</button>
</div>
</div>
<br /><br /><br />
#* Reclamation table *#
<table id="tblReclamations" class="tableData" width="80" border="0" cellpadding="0"
cellspacing="0">
<thead>
<tr>
<th>Reclamation ID</th>
<th>Title</th>
<th>Description</th>
<th>Status</th>
<th>Responsible</th>
<th>Comment</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="Rec in Reclamations | filter: searchFilter" ng-class-odd="'odd'" ng-class-
even="'even'">
<td>{{Rec.RecId}}</td>
<td>{{Rec.RecTitle}}</td>
<td>{{Rec.RecDescription}}</td>
<td>{{Rec.RecStatus}}</td>
<td>{{Rec.RecResponsible}}</td>
<td>{{Rec.RecComment}}</td>
<td>
<button ng-click="UpdateReclamation(Rec); showAddAndEditModalFunction()"
class="btn btn-primary a-btn-slide-text">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
<span><strong>Edit</strong></span>
</button>
<a ng-click="DeleteReclamation(Rec)" class="btn btn-danger a-btn-slide-text">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<span><strong>Delete</strong></span>
</a>
</td>
</tr>
</tbody>
</table>
#* Add and edit part *#
<br /><br /><br /><br />
<div ng-show="showAddAndEditModal" class="form-horizontal" role="form">
<div class="container">
<div class="row">
<h2>
<span id="spn">Add New Reclamation</span>
</h2>
</div>
<div class="row">
#*<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Date :</label>
<div class="col-md-8">
<input type="date" class="form-control" id="inputDate" placeholder="Date"
ng-model="RecDate">
</div>
</div>
</div>*#
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Title :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputTitle"
placeholder="Title" ng-model="RecTitle">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Description :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputDescription"
placeholder="Description" ng-model="RecDescription">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Status :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputStatus"
placeholder="Status" ng-model="RecStatus">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Responsible :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputResponsible"
placeholder="Responsible" ng-model="RecResponsible">
</div>
</div>
</div>
<div class="col-sm-6 col-lg-4">
<div class="form-group">
<label class="col-md-4 control-label">Comment :</label>
<div class="col-md-8">
<input type="text" class="form-control" id="inputComment"
placeholder="Comment" ng-model="RecComment">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 col-lg-4">
<input type="button" id="btnSave" class="form-control btn-space" value="Submit"
ng-click="InsertData()" />
</div>
</div>
</div>
</div>
</div>
#Html.Hidden("RecID_")
</div>
#section scripts {
<script src="//cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js">
</script>
<script src="~/Scripts/app/controllers/reclamations-controller.js"></script>
<script src="~/Scripts/app/controllers/import-controller.js"></script>
<script>
function refreshPage() {
window.location.reload();
}
</script>
}
DataController :
public JsonResult Get_AllReclamation ()
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
List<Reclamation> Rec = Obj.Reclamations.ToList();
return Json(Rec, JsonRequestBehavior.AllowGet);
}
}
public JsonResult Get_ReclamationById (string Id)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
int RecId = int.Parse(Id);
return Json(Obj.Reclamations.Find(RecId), JsonRequestBehavior.AllowGet);
}
}
public string Insert_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
if (ModelState.IsValid)
{
try
{
Obj.Reclamations.Add(Rec);
Obj.SaveChanges();
}
catch (DbEntityValidationException ex)
{
ErrorPrinter(ex.EntityValidationErrors);
}
catch (Exception ex)
{
Console.WriteLine("Exception not managed :");
Console.WriteLine(ex.Message);
}
}
return "Reclamation Added Successfully";
}
}
else
{
return "Reclamation Not Inserted! Try Again";
}
}
public string Update_Reclamation (Reclamation Rec)
{
if (Rec != null)
{
using (GestReclamationDBEntities Obj = new GestReclamationDBEntities())
{
Reclamation RecObj = Obj.Reclamations.Where(a => a.RecId ==
Rec.RecId).FirstOrDefault();
RecObj.RecTitle = Rec.RecTitle;
RecObj.RecDescription = Rec.RecDescription;
RecObj.RecStatus = Rec.RecStatus;
RecObj.RecResponsible = Rec.RecResponsible;
RecObj.RecComment = Rec.RecComment;
Obj.SaveChanges();
return "Reclamation Updated Successfully";
}
}
else
{
return "Reclamation Not Updated! Try Again";
}
}
Thank you !
Related
Im writing an application that connects to an API and allows users to do CRUD operations
In the Frontend.
I Have a button on each row in a table that is called 'View' once clicked, it should copy the info from the row that it was clicked on, into text fields for updating user details.
Table with button
Update Filed after click
I have a debugger under the FillStudentInfo: function (studentId) {} Method and when I debug i can see that the correct record is in the json response, but it doestn seem to add it to the text fields for some reason
Debugger
As you can see, the update field is blank.
StudentSummary.js
var StudentSummaryManager = {
GetAllStudents: function () {
var obj = "";
var serviceUrl = "https://localhost:5001/api/student";
AjaxManager.GetAPI(serviceUrl, onSuccess, onFailed);
function onSuccess(jsonData) {
obj = jsonData;
}
function onFailed(error) {
alert(error.statusText);
}
return obj;
},
GetStudentById: function (studentId) {
var obj = "";
var serviceUrl = "https://localhost:5001/api/student/" + studentId;
AjaxManager.GetAPI(serviceUrl, onSuccess, onFailed);
function onSuccess(jsonData) {
obj = jsonData;
}
function onFailed(error) {
alert(error.statusText);
}
return obj;
}
};
var StudentSummaryHelper = {
InitStudentSummary: function () {
StudentSummaryHelper.LoadStudent();
},
LoadStudent: function () {
$("#Table tbody tr").remove();
var studentList = StudentSummaryManager.GetAllStudents();
$.each(studentList, function (i, item) {
var rows = "<tr>" +
"<td>" + item.StudentId + "</td>" +
"<td>" + item.FirstName + "</td>" +
"<td>" + item.LastName + "</td>" +
"<td>" + item.DateofEnrollment + "</td>" +
"<td>" + item.Active + "</td>" +
"<td><button class='btn btn-info' onClick='StudentSummaryHelper.FillStudentInfo(" + item.StudentId + ")'>View</button></td>" +
"</tr>";
$("#Table tbody").append(rows);
});
},
FillStudentInfo: function (studentId) {
debugger;
var studInfo = StudentSummaryManager.GetStudentById(studentId);
$("#btnSave").text("Update");
$("#divDetails").show();
$("#divSummary").hide();
$("#txtStudentFirstName").val(studInfo.FirstName);
$("#txtStudentLastName").val(studInfo.LastName);
$("#txtStudentDate").val(studInfo.DateofEnrollment);
$("#txtStudentActive").val(studInfo.Active);
}
}
StudentSummary.cshtml
<script src="~/js/Student/StudentSummary.js"></script>
<div class="row">
<div class="col-12">
<h4>Summary of all students</h4>
</div>
<div class="col-md-12">
<button class="btn btn-success" id="btnAdd">Add Student</button>
<table class="table table-striped" id="Table">
<thead>
<tr>
<th>StudentId</th>
<th>FirstName</th>
<th>LastName</th>
<th>DateofEnrollment</th>
<th>Active</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
StudentDetails.js
var StudentDetailsManager = {
SaveStudent: function () {
var obj = StudentDetailsHelper.CreateStudObj();
var objStudent = JSON.stringify(obj);
var serviceUrl = "https://localhost:5001/api/student/AddStudent"
AjaxManager.PostApi(serviceUrl, objStudent, onSuccess, onFailed)
function onSuccess(jsonData) {
if (jsonData.FirstName !== "") {
$("#divDetails").hide();
$("#divSummary").show();
StudentSummaryHelper.LoadStudent();
alert("Saved Successfully");
}
else {
alert(jsonData);
}
}
function onFailed(error) {
alert(error.statusText);
}
}
};
var StudentDetailsHelper = {
InitStudentDetails: function () {
$("#btnAdd").click(function () {
$("btnSave").text("Save");
$("#divDetails").show();
$("#divSummary").hide();
StudentDetailsHelper.ClearForms();
});
$("#btnSave").click(function () {
StudentDetailsManager.SaveStudent();
});
},
CreateStudObj: function () {
debugger;
var obj = new Object();
obj.FirstName = $("#txtStudentFirstName").val();
obj.LastName = $("#txtStudentLastName").val();
obj.DateofEnrollment = $("#txtStudentDate").val();
if ($("#txtStudentActive").is(":checked")) {
obj.Active = "true"
} else {
obj.Active = "false"
}
return obj;
},
ClearForms() {
$("#txtStudentFirstName").val("");
$("#txtStudentLastName").val("");
$("#txtStudentDate").val("");
$("txtStudentActive").val(null);
}
}
StudentDetails.cshtml:
<script src="~/js/Student/StudentDetails.js"></script>
<div class="col-6">
<div class="form-group">
<input type="hidden" id="hdnStudentId" value="0" />
<label class="col-md-3 col-xl control-label" for="txtStudentFirstName">First Name:</label>
<div class="col-md-7 col-xs-7">
<input type="text" class="form-control" id="txtStudentFirstName" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentLastName">Last Name:</label>
<div class="col-md-7 col-xs-7">
<input type="text" class="form-control" id="txtStudentLastName" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentDate">Enrollment Date:</label>
<div class="col-md-7 col-xs-7">
<input type="date" class="form-control" id="txtStudentDate" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 col-xl control-label" for="txtStudentActive">Active:</label>
<div class="col-md-7 col-xs-7">
<input type="checkbox" class="form-control" id="txtStudentActive" />
</div>
</div>
<div class="row">
<div class="spacer5"></div>
<div class="col-md-12 col-xs-12">
<ul class="list-group">
<li class="list-group-item centerAlign">
<button id="btnSave" class="btn btn-success" type="button">Save</button>
</li>
</ul>
</div>
</div>
</div>
So for some reason in the FillStudentInfo: function (studentId) {}
Method I needed to ad a $.each even though the response was only 1 Student.
Heres the fixed method that works:
FillStudentInfo: function (studentId) {
debugger;
var studInfo = StudentSummaryManager.GetStudentById(studentId);
$("#btnSave").text("Update");
$("#divDetails").show();
$("#divSummary").hide();
$.each(studInfo, function (i, studInfo) {
$("#txtStudentFirstName").val(studInfo.FirstName);
$("#txtStudentLastName").val(studInfo.LastName);
$("#txtStudentDate").val(studInfo.DateofEnrollment);
$("#txtStudentActive").val(studInfo.Active);
});
}
When I am trying to import an excel more than 33 columns I have this error.
An item with the same key has already been added. Key: [0, SEX]
[0,SEX] is my 34th column
I am converting file to an Isheet object. It's working fine when it's under 33 columns.
Also It's working on a different project. I am using it exactly same way here too. I checked versions of some packages but couldn't find the problem.
This is my controller.
public async Task<IActionResult> YeniUyeAktarimUpload()
{
try
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadExcel";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
Stream stream = file.OpenReadStream();
using (stream)
{
ISheet sheet;
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //I GET ERROR HERE
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
}
await _aktarimlarService.YeniUyeAktarim(sheet);
return RedirectToAction("YeniUyeAktarim","Aktarimlar");
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
TempData["ErrorMessage"] = "Duyurular getirilirken hata oluştu. Lütfen daha sonra tekrar deneyiniz. ";
return RedirectToAction("Error", "HomeKurum", new { returnUrl = "/Aktarimlar/YeniUyeAktarim" });
}
}
and this is my view
<section class="content">
<div class="card card-primary card-outline">
<div class="card-header">
<h2 class="card-title">Yeni Üye Aktarım</h2>
</div>
<!-- /.card-header -->
<div class="card-body">
<form asp-controller="Home" asp-action="Export">
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="file" id="fileupload" name="files" class="form-control" />
</div>
<div class="col-md-3">
<input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
Download
</div>
<div class="col-md-5">
<input type="submit" name="Export" value="Create and Export" id="btnExport" class="btn btn-primary" asp-action="Export" />
</div>
</div>
<div class="clearfix"> </div>
<div class="row">
<div id="divPrint"></div>
</div>
</div>
</form>
<a class="text-danger" href="~/Downloads/AKTARIM_TASLAK/YeniUyeAktarim.xlsx">Taslak indir</a>
<img width="50" height="40" src="~/images/excel-indir.png" />
#if (TempData.ContainsKey("ErrorMessage"))
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
#TempData["ErrorMessage"]
</div>
}
</div>
</div>
And this is my jquery code
<script type="text/javascript">$(function () {
$('#btnupload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Aktarimlar/YeniUyeAktarimUpload",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#divPrint').html(response);
}
},
error: function (e) {
$('#divPrint').html(e.responseText);
}
});
})
$('#btnExport').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file then Import");
return false;
}
});
});</script>
Thanks for your help..
I am going to pass external object list with form-data in submitHandler section. When i am passing form object only it is working properly. but i want to add list of object to that ajax post request.
JS
submitHandler: function (e) {
$(".loader-showhide").show();
var contacts = [
{ name: 'test 1', mobile: '11111111' },
{ name: 'test 2', mobile: '22222222' }
];
var dataToPost = JSON.stringify({ contacts: contacts });
var form = $(e);
form.find(":submit").attr("disabled", true);
$.ajax(form.attr("action"),
{
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: { model: $(form).serialize(), contacts: dataToPost },
cache: false,
success(data) {
$(".loader-showhide").hide();
$("#myModal").modal('hide');
var table = $('#dt_account').DataTable();
table.ajax.reload();
toastr.success('Successfully added.');
$('#submitBtn').prop("disabled", false);
},
error(xhr) {
}
});
}
Controller
[HttpPost]
public ActionResult Create(ActivityViewModel model, List<Contact> contacts)
{
try
{
int result = 0;
return Json(new { StatusCode = result });
}
catch (Exception ex)
{
throw ex;
}
}
Object
public class Contact
{
public string Name { get; set; }
public string Mobile { get; set; }
}
Here is my form, I used jquery datatable and jquery form submit with submit handler.
<form action="#Url.Action("Create", "Activity")" id="account-form" method="POST" novalidate="novalidate" enctype="multipart/form-data">
<div class="form-blocker-wrap">
#Html.HiddenFor(o => o.Id)
<div class="card-block row">
<div class="col-lg-12">
<div class="scroller bottom-box px-3">
<div class="row">
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="Name">Activity Name</label>
#Html.TextBoxFor(o => o.Name, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="StartDateTime">Start Date</label>
#Html.TextBoxFor(o => o.StartDateTime, new { type = "date", maxlength = 100, placeholder = "Start Date", #class = "form-control", required = "true" })
</div>
<div class="col-md-3 form-group">
<label asp-for="EndDateTime">End Date</label>
#Html.TextBoxFor(o => o.EndDateTime, new { type = "date", maxlength = 100, placeholder = "End Date", #class = "form-control", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div class="col-md-6 form-group">
<label asp-for="ContactType">Select Method</label><br />
#Html.DropDownListFor(o => o.ContactType, (IEnumerable<SelectListItem>)Model.ContactList, new { maxlength = 100, placeholder = "Campaign Name", #class = "form-control", #onchange = "ChangeMethod(this)", required = "true" })
</div>
</div>
<div class="col-lg-12 py-5 px-4 border-right">
<div disabled class="col-md-6 grl-section">
<div class="col-lg-12 form-group">
#for (int i = 0; i < Model.GRLContactGroupList.Count(); i++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].IsChecked) #(#Model.GRLContactGroupList[i].GroupName + " - " + #Model.GRLContactGroupList[i].ZONE) <br />
#for (int j = 0; j < Model.GRLContactGroupList[i].GRLContactList.Count(); j++)
{
#Html.CheckBoxFor(m => m.GRLContactGroupList[i].GRLContactList[j].IsChecked) #Model.GRLContactGroupList[i].GRLContactList[j].Name <br />
}
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer modal-footer py-4">
<div class="row">
<div class="col-lg-6 px-4">
<button id="submitBtn" type="submit" class="btn btn-primary">Save</button>
<button type="reset" class="btn btn-default color-theme">Clear</button>
</div>
</div>
</div>
</form>
I have an array which is referred to an api controller and it's response status is 200. While consoling the array , i have the expected data into it.
But when i try to bind that with aspx using ng-options directive, the dropdown is not populated.
Angular Code:
ERMApp.controller("CascadeDeleteController",
function ($scope, $http, $sce, $rootScope, commondatafactory, academicsetupfactory) {
$rootScope.loading = true;
$scope.successMessage = "";
$scope.successMessageHtml = "";
$scope.errorMessage = "";
$scope.errorMessageHtml = "";
$scope.errorLabelStyle = { color: 'red' };
$scope.PrimaryTables = [];
$scope.PrimaryTableNames = [];
$scope.newCascade = Object.create(null);
$scope.showForm = true;
$scope.reset = function () {
$scope.newCascade = Object.create(null);
};
$scope.validation = function () {
$scope.successMessage = "";
$scope.successMessageHtml = "";
$scope.errorMessage = "";
$scope.errorMessageHtml = "";
var messages = "";
var validationResults = regula.validate();
for (var i = 0; i < validationResults.length; i++) {
var validationResult = validationResults[i];
messages += validationResult.message + "<br />";
$scope.errorMessage = messages;
}
if ($scope.errorMessage.length > 0) {
window.scrollTo(0, 0);
$scope.errorMessageHtml = $sce.trustAsHtml(angular.copy($scope.errorMessage));
}
}
jQuery(document).ready(function () {
regula.bind();
jQuery("#parentTable").blur(function () {
$scope.newCascade.ParentTable = jQuery("#parentTable").val();
$scope.getParentField($scope.newCascade.ParentTable);
});
});
$scope.cancel = function () {
$scope.showForm = false;
$scope.successMessage = "";
$scope.successMessageHtml = "";
$scope.errorMessage = "";
$scope.errorMessageHtml = "";
$scope.loadData();
}
$scope.ParentTableNames = function () {
$http.get('/api/CommonData/GetTableNameList')
.success(function(data, status) {
$rootScope.loading = false;
$scope.PrimaryTableNames = [];
$scope.PrimaryTableNames = data;
//console.log($scope.PrimaryTableNames);
$("#parentTable").kendoAutoComplete({
dataSource: data,
filter: "startswith",
minLength: 3
});
if ($scope.PrimaryTableNames && $scope.PrimaryTableNames.length)
$scope.showForm = false;
});
}
$scope.ParentTableNames();
$scope.getParentField = function (parentField) {
$http.get("/api/CommonData/GetParentField?parentField=" + parentField)
.success(function (data, status) {
$rootScope.loading = false;
$scope.PrimaryTables = [];
$scope.PrimaryTables = data;
console.log($scope.PrimaryTables);
if ($scope.PrimaryTables && $scope.PrimaryTables.length)
$scope.showForm = false;
});
}
$scope.Add = function () {
$scope.newSemesterConfiguration = Object.create(null);
$scope.showForm = true;
$scope.successMessage = "";
$scope.successMessageHtml = "";
$scope.errorMessage = "";
$scope.errorMessageHtml = "";
}
});
The Binding part in aspx:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/App_MasterPages/BackOfficeMasterPage.master" CodeBehind="CascadeDelete.aspx.cs" Inherits="ERMAdmin_Inc.administration.CascadeDelete" %>
<h4>Cascade Delete Configuration Setup</h4>
<ul class="breadcrumb">
<li><i class="glyphicon glyphicon-home"></i></li>
<li>Administration</li>
<li>Cascade Delete Configuration Setup</li>
</ul>
<script src="../Scripts/ScriptAdmin/angularControllers/Administration/CascadeDeleteSetupController.js"></script>
<div data-ng-controller="CascadeDeleteController" id="angularpage"></div>
<div ng-show="successMessage.length" id="successmessageDiv" class="alert alert-success alert-block fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="fa fa-times"></i>
</button>
<p>{{successMessage}}</p>
</div>
<div ng-show="errorMessage.length" id="errormessageDiv" class="alert alert-block alert-danger fade in">
<button data-dismiss="alert" class="close close-sm" type="button">
<i class="fa fa-times"></i>
</button>
<p ng-bind-html="errorMessageHtml"></p>
</div>
<div class="row">
<div class="col-sm-8">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title"> Add / Edit Cascade Delete</h4>
</div>
<div class="panel-body nopadding">
<div class="form-horizontal form-bordered">
<div class="form-group">
<label class="col-lg-4 col-sm-2 control-label">Parent Table</label>
<div class="col-sm-8">
<input id="parentTable" type="text" class="form-control"
data-constraints='#Required(message = "Parent Table is required.")'
data-ng-model="newCascade.ParentTable">
<span class="mandatoryFieldMarker">*</span>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 col-sm-2 control-label">Parent Field Name</label>
<div class="col-sm-8">
<select
data-ng-model="newCascade.ParentTableField"
data-ng-options="o.COLUMN_NAME for o in PrimaryTables"
class="form-control mandatoryfield"
data-constraints='#Required(message = "ParentTableField is required.")'
>
<option value="">Please Select</option>
<%--<option value="">All Departments</option>--%>
</select>
<span class="mandatoryFieldMarker">*</span>
</div>
</div>
<div class="btn-list" style="text-align: right; margin-right: 1.5%">
<i class="fa fa-check"></i>Save
<i class="fa fa-trash-o"></i>Cancel
<i class="fa fa-backward"></i>Back to List
<i class="fa fa-backward"></i>Save and Add more
</div>
</div>
</div>
</div>
</div>
</div>
<div data-ng-show="PrimaryTables.length && !showForm">
<div style="text-align: right">
<i class="fa fa-plus"></i>Add New
<br />
<br />
</div>
</div>
PrimaryTables is bound to the $scope of the CascadeDeleteController.
However, the ngController is placed on a div, which is immediately closed.
<div data-ng-controller="CascadeDeleteController" id="angularpage"></div>
What you need is
`<div data-ng-controller="CascadeDeleteController" id="angularpage">
{{PrimaryTables}}
<-- select with ngOptions here
</div>`
As can be seen in this picture I have a list of missing dates I have not reported a time for, and when I click a date I have missed my 'Rappotera tid' gets filled in with that date.
But what I want to do is I want to remove my 'Datum' have it sole based on the check boxes that are before the date, so at at a later date can report several dates at once.
But I am stuck and I would like to get some help.
This is my view:
<script type="text/javascript" language="javascript">
$(function() {
$(function() {
$('#date').datepicker({
showButtonPanel: true,
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd",
firstDay: 1,
onSelect: function(dateText) {
$('#EndDate').datepicker('option', 'minDate', new Date(dateText));
}
});
});
});
function SetDate(dt) {
$('#date').val(dt);
}
var n = #(Model.Projects.Count);;
function AddProject() {
n++;
$.ajax({
type: "GET",
url: "#Url.Action("Project")/" + n,
dataType: "html",
success: function(data) {
$('#projects').append(data);
}
});
}
$(function() {
$('#startTime').change(function() { CalculateTime(); });
$('#endTime').change(function() { CalculateTime(); });
$('#breakTime').change(function() { CalculateTime(); });
CalculateTime();
});
function CalculateTime() {
try {
var startTime = $('#startTime').val();
var endTime = $('#endTime').val();
var breakTime = $('#breakTime').val();
var startDate = new Date(2000, 1, 1, startTime.substring(0, 2), startTime.substring(3, 5), 0, 0);
var endDate = new Date(2000, 1, 1, endTime.substring(0, 2), endTime.substring(3, 5), 0, 0);
var time = endDate - startDate;
time = time / 1000 / 60 / 60;
time = time - breakTime.substring(0, 2);
time = time - (breakTime.substring(3, 5) / 60);
$('#workedHours').html(time + " timmar");
} catch (err) {
$('#workedHours').html("---");
}
}
</script>
<div class="page-container">
<div class="page-content">
<div class="container">
<div class="row">
<div class="col-md-12">
#if (ViewData["posted"] != null)
{
<div class="alert alert-success">
<strong>Tidsrapporten tillagd.</strong>
</div>
}
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">missad rappoterad tid</span>
</div>
</div>
<form class="form-horizontal">
<div class="portlet-body form">
<div class="form-group">
#foreach (var date in ViewBag.MissingDays)
{
var isoDate = date.ToString("yy-MM-dd");
<div class="col-md-1">
<input type="checkbox" name="Date" value="Date">
#isoDate
</div>
}
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#Html.ValidationSummary()
#using (Html.BeginForm("TimeReport", "Reports", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal" }))
{
#Html.Hidden("ReportId", Model.ReportId)
<div class="col-md-6">
<div class="tabbable tabbable-custom tabbable-noborder tabbable-reversed">
<div class="tab-content">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-sharp bold uppercase">Rappotera tid</span>
</div>
</div>
<div class="portlet-body form">
<div class="form-group">
<label class="col-md-3 control-label">Datum:</label>
<div class="col-md-5">
#Html.TextBox("date", Model.Date.ToShortDateString(), new {#class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Start tid:</label>
<div class="col-md-5">
#Html.TextBox("startTime", Model.Times.StartTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Slut tid:</label>
<div class="col-md-5">
#Html.TextBox("endTime", Model.Times.EndTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Rast Längd:</label>
<div class="col-md-5">
#Html.TextBox("breakTime", Model.Times.BreakTime, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Tid jobbad:</label>
<div class="col-md-5">
#Html.TextBox("workedHours", Model.Times.WorkedHours, new { #class = "form-control timepicker timepicker-24" })
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div id="projects">
#foreach (var data in Model.Projects)
{
Html.RenderPartial("Project", data, ViewData["vd"] as ViewDataDictionary);
var viewDataDictionary = ViewData["vd"] as ViewDataDictionary;
if (viewDataDictionary != null)
{
viewDataDictionary["id"] = (int)viewDataDictionary["id"] + 1;
}
}
</div>
</div>
<div class="form-actions">
<div class="col-md-offset-4 col-asdfasmd-9">
Lägg till projekt
<button type="submit" class="btn btn-primary">Spara</button>
</div>
</div>
if (Model.ReportId.HasValue)
{
<input type="submit" value="Ta bort" name="delete" />
}
}
</div>
</div>
</div>
</div>
And this is my controller for this view:
public ActionResult TimeReport(FormCollection form, Guid? id)
{
ViewDataDictionary vd = new ViewDataDictionary
{
["projects"] = new DatabaseLayer().GetConsultantProjects(Constants.CurrentUser(User.Identity.Name)),
["id"] = 1,
["showDescription"] = true
};
ViewData["vd"] = vd;
NewTimeReportModel projectData = new NewTimeReportModel();
if (form != null && form.AllKeys.Contains("delete"))
{
new DatabaseLayer().DeleteTimeReport(Guid.Parse(form["ReportId"]));
LoadDefaultSettings(projectData);
ViewData.Model = projectData;
return View();
}
if (id.HasValue && (form == null || form.AllKeys.Length == 0))
{
using (DatabaseLayer db = new DatabaseLayer())
{
var timeReport = db.GetTimeReport(id.Value);
projectData = new NewTimeReportModel(timeReport);
if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
else if (form == null || form.AllKeys.Length == 0)
{
LoadDefaultSettings(projectData);
}
else
{
DateTime reportDate;
if (!DateTime.TryParse(form["date"], out reportDate))
ModelState.AddModelError("Date", "Felaktikt datum");
var projectNumbers = (from x in form.AllKeys
where x.Contains("_")
select x.Substring(x.IndexOf('_'))).Distinct();
projectData.Times = new TimeReportTimes(form["startTime"], form["endTime"], form["breakTime"], ModelState);
projectData.Date = reportDate;
if (!projectNumbers.Any())
ModelState.AddModelError("Projekt", "Inga projekt valda...");
else
{
int emptyHours = 0;
foreach (string projectNumber in projectNumbers)
{
projectData.Projects.Add(new NewTimeReportModel.Project
{
Description = form["description" + projectNumber],
Hours = null,
ProjectId = Guid.Parse(form["project" + projectNumber])
});
string hourString = form["hours" + projectNumber];
if (string.IsNullOrEmpty(hourString))
{
emptyHours++;
projectData.Projects[projectData.Projects.Count - 1].Hours = projectData.Times.WorkedHours;
}
else
{
if (!projectData.Projects[projectData.Projects.Count - 1].SetHours(hourString))
{
ModelState.AddModelError("hours_" + projectNumber, "Felaktig antal timmar");
}
}
}
if (emptyHours > 1 || (emptyHours == 0 && projectData.Projects.Sum(x => x.Hours) != projectData.Times.WorkedHours))
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar stämmer ej överrens");
}
if (projectData.Projects.Where(x => x.Hours <= 0).Any())
{
ModelState.AddModelError("hours_" + projectNumbers.First(), "Antalet timmar måste vara större än noll");
}
if (!string.IsNullOrEmpty(form["ReportId"]))
projectData.ReportId = Guid.Parse(form["ReportId"]);
if (ModelState.IsValid)
{
projectData.SaveToDatabase(Constants.CurrentUser(User.Identity.Name));
ViewData["posted"] = true;
projectData = new NewTimeReportModel();
LoadDefaultSettings(projectData);
}
else if (projectData.Projects.Count == 1)
projectData.Projects[0].Hours = null;
}
}
var missingdays = new DatabaseLayer().GetConsultantMissingDays(Constants.CurrentUser(User.Identity.Name));
if (missingdays.Count == 0)
{
ViewData["missingDays"] = "";
}
else
{
ViewBag.MissingDays = missingdays;
}
ViewData.Model = projectData;
return View();
}