Text fields not updating with user detail from VIEW button - c#

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);
});
}

Related

Add and Edit methods do not work properly

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 !

How to pass external object list and form object in ajax to mvc controller

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>

Ajax.Get Call not firing in Partial Views when master page loads

I am trying to set a master page Employee Qualifications, this master page will include other views suck as work experience, employee skills, education.
In each partial view i have an ajax get method that brings the data and returns on success to render the partial view. the problem is that the method LoadWorkExperiences(); never gets fired when i navigate to the master page and hence the data is never loaded in view.
I am doing it this way because i want to open an edit popup window by clicking of the button. there for loading directly to master page is not my option.
Thanks for your help.
I tried calling "HumanResourse/WorkExperience/DisplayWorkExperience/15" and it also does not fire the Ajax call.
the Master View cshtml HERE.
#{
ViewBag.Title = "Display";
Layout = "~/Areas/HumanResourse/Views/Shared/_LayoutHRUB.cshtml";
int EmpId = ViewBag.EmployeeId;
}
<h2>Qualifications</h2>
<div>
<p>Work Experience</p>
#Html.Action("DisplayWorkExperience", "WorkExperience", new { id = EmpId })
</div>
<div>
<p>Education</p>
#Html.Action("DisplayEducation", "Education", new { id = EmpId })
</div>
the sub view code DisplayWorkExperience HERE.
#model SaaS.Areas.HumanResourse.Models.HR_Emp_WorkExperience_ViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<title>DisplayWorkExperience</title>
</head>
<body>
<input class="hidden" id="EmpId" value="#ViewBag.EmployeeId" />
<div class="container">
<label>Work Experiences</label>
Add New Work Experience <br /><br />
<table id="tblWorkExperience" class="table table-striped">
<thead>
<tr>
<th>Company</th>
<th>Position</th>
<th>From</th>
<th>To</th>
<th>Comment</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
#*Create A Popup Modal With Registration Form For Add Or Edit Student Record*#
<div class="modal fade" id="MyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<form id="form">
<fieldset id="SubmitForm">
#Html.HiddenFor(m => m.HR_Emp_WorkExperienceId, new { #id = "WorkExperienceId" })
<div class="form-group">
#Html.TextBoxFor(m => m.CompanyName, new { #id = "CompName", #class = "form-control", #placeholder = "Company Name*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Position, new { #id = "Position", #class = "form-control", #placeholder = "Position*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.From, new { #id = "DateFrom", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.To, new { #id = "DateTo", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Comment, new { #id = "Position", #class = "form-control", #placeholder = "Comment" })
</div>
<div class="form-group">
Save
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
#section scripts
{
<script type="text/javascript">
$(Document).ready(function () {
$("#LoadingStatus").html("Loading....");
LoadWorkExperiences();
});
//Start LoadWorkExperiences
function LoadWorkExperiences() {
$("#tblWorkExperience tbody tr").remove();
var EmpId = $("#EmpId").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmpWorkExperiences", "WorkExperience", new {id = "ID"})'.replace("ID", EmpId),
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='h5'>" + item.CompanyName + "</td>"
+ "<td class='h5'>" + item.Position + "</td>"
+ "<td class='h5'>" + item.From + "</td>"
+ "<td class='h5'>" + item.To + "</td>"
+ "<td class='h5'>" + item.Comment + "</td>"
+ "<td>" + "<a href='#' class='btn btn-warning' onclick='EditWorkExperience(" + item.HR_Emp_WorkExperienceId + ")' ><span class='glyphicon glyphicon-edit'></span></a>" + "</td >"
+ "<td>" + "<a href='#' class='btn btn-danger' onclick='DeleteWorkExperience(" + item.HR_Emp_WorkExperienceId + ")'><span class='glyphicon glyphicon-trash'></span></a>" + "</td>"
+ "</tr>";
$("#tblWorkExperience tbody").append(rows);
$("#LoadingStatus").html(" ");
});
},
error: function (ex) {
var r = jQuery.parseJSON(Response.text);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
}
});
};
</script>
}
The Controller Code HERE.
public class WorkExperienceController : Controller
{
ApplicationDbContext Db;
public WorkExperienceController()
{
Db = new ApplicationDbContext();
}
// GET: HumanResourse/WorkExperience
public ActionResult Index()
{
return View();
}
public ActionResult DisplayWorkExperience(int? id)
{
TempData["EmployeeId"] = id;
ViewBag.EmployeeId = id;
return View();
}
public JsonResult GetEmpWorkExperiences(int? id)
{
if (id == null)
{
throw new HttpException(404, "Bad Request");
}
var EmpQualification = Db.HR_Emp_Qualifications.SingleOrDefault(p => p.HR_Emp_QualificationId == id);
if (EmpQualification == null)
{
throw new HttpException(404, "Not Found");
}
List<HR_Emp_WorkExperience_ViewModel> EmpWorkExpList = EmpQualification.HR_Emp_WorkExperiences.Select(x => new HR_Emp_WorkExperience_ViewModel
{
HR_Emp_WorkExperienceId = x.HR_Emp_WorkExperienceId,
CompanyName = x.CompanyName,
Position = x.Position,
From = x.From,
To = x.To,
Comment = x.Comment
}).ToList();
return Json(EmpWorkExpList, JsonRequestBehavior.AllowGet);
}
}
i am getting now this error
Failed to construct 'Document': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
I think you can rework what you have here, and it should work, like so:
Index.cshtml:
#{
ViewBag.Title = "Display";
Layout = "~/Areas/HumanResourse/Views/Shared/_LayoutHRUB.cshtml";
int EmpId = ViewBag.EmployeeId;
}
#section scripts
{
<script>
$(function () {
$("#LoadingStatus").html("Loading....");
LoadWorkExperiences();
});
//Start LoadWorkExperiences
function LoadWorkExperiences() {
$("#tblWorkExperience tbody tr").remove();
var EmpId = $("#EmpId").val();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmpWorkExperiences", "WorkExperience")/' + EmpId,
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var rows = "<tr>"
+ "<td class='h5'>" + item.CompanyName + "</td>"
+ "<td class='h5'>" + item.Position + "</td>"
+ "<td class='h5'>" + item.From + "</td>"
+ "<td class='h5'>" + item.To + "</td>"
+ "<td class='h5'>" + item.Comment + "</td>"
+ "<td>" + "<a href='#' class='btn btn-warning' onclick='EditWorkExperience(" + item.HR_Emp_WorkExperienceId + ")' ><span class='glyphicon glyphicon-edit'></span></a>" + "</td >"
+ "<td>" + "<a href='#' class='btn btn-danger' onclick='DeleteWorkExperience(" + item.HR_Emp_WorkExperienceId + ")'><span class='glyphicon glyphicon-trash'></span></a>" + "</td>"
+ "</tr>";
$("#tblWorkExperience tbody").append(rows);
$("#LoadingStatus").html(" ");
});
},
error: function (ex) {
var r = jQuery.parseJSON(Response.text);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
}
});
};
</script>
}
<h2>Qualifications</h2>
<div>
<p>Work Experience</p>
#Html.Action("DisplayWorkExperience", "WorkExperience", new { id = EmpId })
</div>
<div>
<p>Education</p>
#Html.Action("DisplayEducation", "Education", new { id = EmpId })
</div>
DisplayWorkExperience.cshtml (displayed as a partial view):
<input class="hidden" id="EmpId" value="#ViewBag.EmployeeId" />
<div class="container">
<label>Work Experiences</label>
Add New Work Experience <br /><br />
<table id="tblWorkExperience" class="table table-striped">
<thead>
<tr>
<th>Company</th>
<th>Position</th>
<th>From</th>
<th>To</th>
<th>Comment</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
#*Create A Popup Modal With Registration Form For Add Or Edit Student Record*#
<div class="modal fade" id="MyModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
×
<h4 id="ModalTitle"></h4>
</div>
<div class="modal-body">
<form id="form">
<fieldset id="SubmitForm">
#Html.HiddenFor(m => m.HR_Emp_WorkExperienceId, new { #id = "WorkExperienceId" })
<div class="form-group">
#Html.TextBoxFor(m => m.CompanyName, new { #id = "CompName", #class = "form-control", #placeholder = "Company Name*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Position, new { #id = "Position", #class = "form-control", #placeholder = "Position*" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.From, new { #id = "DateFrom", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.To, new { #id = "DateTo", #class = "form-control" })
</div>
<div class="form-group">
#Html.TextBoxFor(m => m.Comment, new { #id = "Position", #class = "form-control", #placeholder = "Comment" })
</div>
<div class="form-group">
Save
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
With a few changes to the controller:
public class WorkExperienceController : Controller
{
// ... the rest of your code
[ChildActionOnly] // An attribute which will prevent this action from being called by anything but Html.Action()
public ActionResult DisplayWorkExperience(int? id)
{
TempData["EmployeeId"] = id;
ViewBag.EmployeeId = id;
return PartialView(); // this needs to return a partial view
}
}
This is untested, but if I'm understanding the end result you're after, this should work. Basically:
Move the #section to the full view, Index.cshtml, so that it actually gets rendered. It doesn't matter where in the page you have that - I prefer to put #section calls at the top of the view, but it doesn't affect where that code is injected into the layout.
Change the return type of DisplayWorkExperience to PartialViewResult, so that it doesn't try to render the layout
Add the ChildActionOnlyAttribute to DisplayWorkExperience (optional) - this is purely to indicate that DisplayWorkExperience is only for rendering an embedded view, and will throw an exception if an attempt is made to navigate to that action.
From there, the jQuery code you have should work as I think you intended.

Loaded array is not binding to angular directive in ng-options in a .net app

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>`

FormCollection Empty in ASP.NET Mobile View

When I am using this code as web view, it works fine, but when with developer option in Chrome I select Mobile View, FormCollection shows empty strings in the controller
VIEW (Edit updtaed)
<div class="page product-details-page deal-product-details-page">
#using (Html.BeginForm("AddProductToCart_Details", "DealProduct", new { productId = Model.Id, shoppingCartTypeId = 1 }, FormMethod.Post))
{
<div class="page-body">
#using (Html.BeginRouteForm("Product", new { SeName = Model.SeName }, FormMethod.Post, new { id = "product-details-form" }))
{
#{
var dataDictAttributes = new ViewDataDictionary();
dataDictAttributes.TemplateInfo.HtmlFieldPrefix = string.Format("attributes_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductAttributes.cshtml", Model.ProductAttributes, dataDictAttributes)
}
<!--gift card-->
#{
var dataDictGiftCard = new ViewDataDictionary();
dataDictGiftCard.TemplateInfo.HtmlFieldPrefix = string.Format("giftcard_{0}", Model.Id);
#Html.Partial("~/Views/Product/_GiftCardInfo.cshtml", Model.GiftCard, dataDictGiftCard)
}
<!--rental info-->
#{
var dataDictRental = new ViewDataDictionary();
dataDictRental.TemplateInfo.HtmlFieldPrefix = string.Format("rental_{0}", Model.Id);
#Html.Partial("~/Views/Product/_RentalInfo.cshtml", Model, dataDictRental)
}
<!--price & add to cart-->
#{
var dataDictPrice = new ViewDataDictionary();
dataDictPrice.TemplateInfo.HtmlFieldPrefix = string.Format("price_{0}", Model.Id);
#Html.Partial("~/Views/Product/_ProductPrice.cshtml", Model.ProductPrice, dataDictPrice)
#Html.Partial("~/Views/Product/_ProductTierPrices.cshtml", Model.TierPrices)
}
<!--wishlist, compare, email a friend-->
<!--attributes-->
#{
var item = #Model.AssociateProductAttributesList.Where(x => x.Item1 == data.Id).Select(x => x.Item2).ToList()[0];
bool isAttributes =false;
}
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<br />
#foreach (System.Collections.DictionaryEntry value in item)
{
var val = data.Id + "_" + value.Key.ToString();
isAttributes = true;
#*<div class="attributes">*#
<dl>
<dt id="product_attribute_label_19">
<label class="text-prompt">
#value.Key.ToString()
</label>
</dt>
<dd id="product_attribute_input_19" class="product_attribute_inputdiv_#val">
#Html.DropDownList("Attributes," + data.Id + "," + value.Key.ToString(), new SelectList((System.Collections.IEnumerable)value.Value, "Id", "Name"), "--- Please select ---")
</dd>
</dl>
#*</div>*#
}
<br />
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
#if (item.Count == 0)
{
#Html.Hidden("Attributes," + data.Id + ",", "0")
<div class="popup" data-popup="popup-#data.Id">
<div class="popup-inner">
<h2>#data.Name</h2>
<p>#data.ShortDescription</p>
<div onclick="ImageBlur('div_#data.Id')" class="buttons" style="text-align:left;">
<input class="button-1" data-popup-close="popup-#data.Id" type="button" value="Add to back" />
</div>
<a class="popup-close" data-popup-close="popup-#data.Id" href="#">x</a>
</div>
</div>
}
#if (isAttributes)
{
<a style="color: blue;" data-popup-open="popup-#data.Id" href="#">
<img id="imgdiv_#data.Id" src="~/Themes/Playground/Content/img/dealselectattribut.png" class="select-atr-img" style="width: 50%; margin-bottom: 10px;"/>
</a>
}
</div>
}
</div>
<div>
</div>
#{
var dataDictAddToCart = new ViewDataDictionary();
dataDictAddToCart.TemplateInfo.HtmlFieldPrefix = string.Format("addtocart_{0}", Model.Id);
<div class="overview" style="width:100%; margin-left:auto">
#Html.Partial("~/Views/Product/_AddToCart.cshtml", Model.AddToCart, dataDictAddToCart)
</div>
}
</div>
}
</div>
}
</div>
Controller
public ActionResult AddProductToCart_Details(int productId, int shoppingCartTypeId, FormCollection form)
{
if (_productService.IsDealProducts(productId))
{
if (!IsCompleteSelected(form))
{
return Json(new
{
success = false,
message = " Plese select all associated product attribute "
});
}
}
//more code here
}
Normal View (Web View)
Mobile View
Form in form is not allowed. This is your issue.

Categories

Resources