I need your help...
Primary controller :
#Controller
public class WaitingListController {
#Autowired
private WaitingListRepository waitingListRepo;
#Autowired
private DepartmentRepository depRepo;
#Autowired
private PatientRepository paitentRepo;
#Autowired
private SurgeonRepository surgeonRepo;
#GetMapping("/surgerywaitinglist")
public ModelAndView getAll() {
ModelAndView mav = new ModelAndView("list");
mav.addObject("waitinglist", waitingListRepo.findAll());
return mav;
}
#GetMapping(value="/surgerywaitinglist/patientSearch")
public ModelAndView patientSearch() {
ModelAndView mav = new ModelAndView("patientSearch");
Patient patient =new Patient();
mav.addObject("patient", patient);
return mav;
}
#GetMapping(value="/surgerywaitinglist/addProcedure")
public ModelAndView addProcedure( Long patientId) {
//public ModelAndView addProcedure() {
ModelAndView mav = new ModelAndView("addProcedure");
Patient patient = paitentRepo.findById(patientId).get();
List<Surgeon> surgeons = surgeonRepo.findAll();
List<Department> departments = depRepo.findAll();
WaitingList waitinglist = new WaitingList();
mav.addObject("patient", patient);
mav.addObject("surgeons", surgeons);
mav.addObject("departments", departments);
mav.addObject("waitinglist", waitinglist);
return mav;
}
#PostMapping(value="/surgerywaitinglist/saveToWaitinList")
public String saveToWaitinList(#ModelAttribute WaitingList waitinglist, Long patientId) {
if(waitinglist.getWaitingListId()==null) {
waitinglist.setWaitingListPatientId(patientId);
waitingListRepo.save(waitinglist);
}
else {
waitinglist.setWaitingListActualBookingDate(waitinglist.getWaitingListActualBookingDate());
waitinglist.setWaitingListAdditionDate(waitinglist.getWaitingListAdditionDate());
waitinglist.setWaitingListProcedure(waitinglist.getWaitingListProcedure());
waitinglist.setWaitingListDiagnosis(waitinglist.getWaitingListDiagnosis());
waitinglist.setWaitingListSurgeonId(waitinglist.getWaitingListSurgeonId());
waitinglist.setWaitingListDepartmentId(waitinglist.getWaitingListDepartmentId());
waitingListRepo.save(waitinglist);
}
return "redirect:/surgerywaitinglist";
}
}
Secondary Controller:
package com.WaitingListThymeleaf.controller;
#RestController
public class SurgeonController {
#Autowired
private SurgeonRepository surgeonRepo;
#GetMapping("surgeons")
public List<Surgeon> getAll(){
return surgeonRepo.findAll();
}
#GetMapping("surgeon/{surgeonSpeciality}")
public List<Surgeon> findBySurgeonSpeciality(#PathVariable Long surgeonSpeciality) {
List<Surgeon> surgeons = surgeonRepo.findBySurgeonspeciality(surgeonSpeciality);
return surgeons;
}
}
HTML page (body only):
<body>
<div class="container">
<br />
<h3>Add New Procedure</h3>
<br />
<hr />
<br />
<form th:action="#{saveToWaitinList}" th:object="${waitinglist}"
method="POST">
<table class="table table-primary table-bordered table-striped"
id="employeeTable" style="width: 50%" align="center">
<thead>
</thead>
<tbody>
<tr>
<td>MRN</td>
<td th:text="${patient.patientId}"></td>
</tr>
<tr>
<td>Name</td>
<td
th:text="${patient.patientFirstName} +' '+ ${patient.patientLastName}"></td>
</tr>
<tr>
<td>Gender</td>
<td th:text="${patient.patientGender}"></td>
</tr>
<tr>
<td>Contact</td>
<td th:text="${patient.patientConact}"></td>
</tr>
<tr>
<td>Procedure</td>
<td><input type="text"
th:field="${waitinglist.waitingListProcedure}"
class="form-control col-4 mb-4" placeholder="Enter Procedure" />
</td>
</tr>
<tr>
<td>Diagnosis</td>
<td><input type="text"
th:field="${waitinglist.waitingListDiagnosis}"
class="form-control col-4 mb-4" placeholder="Enter Diagnosis" />
</td>
</tr>
<tr>
<td>Choose Department</td>
<td>
<div id="department">
<select th:field="${waitinglist.waitingListDepartmentId}"
onchange="showCustomer(this.value)">
<option th:each="department: ${departments}"
th:value="${department.departmentId}"
th:text="${department.departmentName}"></option>
</select>
</div>
</td>
<!-- <input type="text"
th:field="${waitinglist.waitingListDepartmentId}"
class="form-control col-4 mb-4" placeholder="Enter Department" /> -->
</tr>
<tr>
<td>Surgeon</td>
<td>
<div id="SurgeonId">
<select>
<option value="" disabled>Select Department First</option>
</select>
</div>
</td>
<!-- Before AJAX Implementation
<td><input type="text"
th:field="${waitinglist.waitingListSurgeonId}"
class="form-control col-4 mb-4" placeholder="Enter MRP" /></td>
-->
</tr>
<tr>
<td>Addition Date</td>
<td><input type="date"
th:field="${waitinglist.waitingListAdditionDate}"
class="form-control col-4 mb-4" placeholder="Pick Date" /></td>
</tr>
<tr>
<td>Acttual Booking Date</td>
<td><input type="date"
th:field="${waitinglist.waitingListActualBookingDate}"
class="form-control col-4 mb-4" placeholder="Pick Date" /></td>
</tr>
</tbody>
</table>
<br />
<hr />
<br /> <input type="hidden" th:field="${patient.patientId}" />
<div style="text-align: center;">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
<br /> <br />
<div style="text-align: center;">
<a th:href="#{/surgerywaitinglist}">Back To List</a>
</div>
</div>
JavaScript AJAX Code:
<script>
function showCustomer(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("SurgeonId").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/surgeon/" + str, false);
xmlhttp.send();
}
On the client side I get the pulled data as JSON as you can see:
How can I manipulate the pulled data into select/option tag in the HTML page?
.... Update....
I edited the AJAX script as follows:
<script>
function showSurgeons(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//var log = xmlhttp.responseText;
//console.log(log);
//const res = JSON.parse(xmlhttp.responseText);
//Object.entries(res).forEach((entry) => {
// const [key, value] = entry;
// console.log(`${key}: ${value}`);
//});
/* xmlhttp.onload = function(){
var ourData = JSON.parse(xmlhttp.responseText);
console.log(ourData);
} */
//document.getElementById("SurgeonId").innerHTML = xmlhttp.responseText;
var ourData = JSON.parse(xmlhttp.responseText);
var innerHTMLTest = '<select th:field="${waitinglist.waitingListSurgeonId}"> ';
for(i=0; i<ourData.length; i++){
innerHTMLTest +=' <option th:value="'+ ourData[i].surgeonId + '" th:text="' + ourData[i].surgeonLastName + '"></option>';
}
innerHTMLTest += ' </select>';
console.log(innerHTMLTest);
//document.getElementById("SurgeonId").innerHTML = ourData.surgeonId;
document.getElementById("SurgeonId").innerHTML = innerHTMLTest;
}
}
xmlhttp.open("GET", "/surgeon/" + str, false);
xmlhttp.send();
}
</script>
It seems it is working-is... In the console I get the following:
<select th:field="${waitinglist.waitingListSurgeonId}"> <option th:value="13505" th:text="Zah"></option> <option th:value="13000" th:text="Abdulkareem"></option> </select>
which is exactly what I needed... However, nothin shows on the template as you can see :
Today's update :)
Apparently, the code works even though it not showing in the select/option as you can see in the attached image below !
When I inspect the document.body (DOM) in the background... It is there! but not visible... I checked the database... the mySQL INSERTed successfully !
Here is the screenshot of the MySQL Workbench:
Successfully added !
Related
An example of the problem:
The page first loads with a list of items in the default order: [0,1,2,3,4,5]
The user rearranges the order to: [4,5,2,3,1,0]
When the serialized form is posted, it is still the default order: [0,1,2,3,4,5]
I think this is happening because the list items are generated at the page load with a set order, and that order does not change when the UI is updated. Is there a way to submit the updated list of SortOrderOptions?
The list of items:
<div class="row">
<ul id="sortable" style="list-style: none; padding-left: 0px; width: 100%;">
#for (var x = 0; x < Model.SortOrderOptions.Count; x++)
{
<li style="width: 100%;">
<div class="row">
<div class="col-6" style="padding-left:30px;">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" asp-for="#Model.SortOrderOptions[x].SortBy" class="sortBox" /><span></span></label>
<label>#Model.SortOrderOptions[x].Name</label>
<input type="hidden" asp-for="#Model.SortOrderOptions[x].Name" value="#Model.SortOrderOptions[x].Name" />
</div>
<div class="col-3 center">
<label asp-for="#Model.SortOrderOptions[x].Subtotal">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="#(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="#Model.SortOrderOptions[x].Subtotal" class="subtotalBox" /><span></span></label>
</label>
</div>
<div class="col-3">
<label asp-for="#Model.SortOrderOptions[x].NewPage">
<label class="kt-checkbox kt-checkbox--brand"><input type="checkbox" disabled="#(Model.SortOrderOptions[x].SortBy != true ? "disabled" : null)" asp-for="#Model.SortOrderOptions[x].NewPage" class="newPageBox" /><span></span></label>
</label>
</div>
</div>
</li>
}
</ul>
</div>
<script src="~/libs/js/jquery.js"></script>
<script src="~/libs/jqueryui/jquery-ui.js"></script>
Javascript:
$("#sortable").sortable({
axis: "y",
containment: "parent"
});
$('#submit').off('click').on('click', function (evt) {
var data = $('form').serialize();
var url = "#Context.Request.Path.Value.Replace("/Test","", StringComparison.OrdinalIgnoreCase)";
evt.preventDefault();
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: dataType,
url: '#Url.Action("PBSCSubmit","Reports")',
beforeSend: function(){
// Show loading spinner while processing
$('#loader').modal({
backdrop: 'static',
keyboard: false
});
},
success: function (data) {
if (data.success) {
//Success with warnings
if (data.warning) {
$('#loader').modal('toggle');
//Toggle the error modal and display messages
$('#errorsModal').modal('toggle');
//Add <br> tags when there is a linebreak in the string. This will add the line breaks into the HTML.
$('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
//Open PDF on warning modal "OK" button click
$('#modalConfirm').on('click', function () {
window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
});
} else {
//Success without warnings
$('#loader').modal('toggle');
window.open(url + "/ShowPDF?path=" + data.pdf, "_blank");
if (data.csvCreated) {
window.open(url + "/DownloadFile?path=" + data.csv + "&fileName=" + CSVFileName, "_blank");
}
}
} else {
$('#loader').modal('toggle');
//Toggle the error modal and display messages
$('#errorsModal').modal('toggle');
//Add <br> tags when there is a linebreak in the string. This will add the line breaks into the HTML.
$('#errorsModal .modal-body p').html(data.message.replace(/(?:\r\n|\r|\n)/g, '<br>'));
}
},
error: function (jqXHR) {
$('#loader').modal('toggle');
handleAjaxError(jqXHR);
}
});
});
Controller:
public IActionResult PBSCSubmit(PaymentsBySelectionCriteria report)
{
var convertedReport = new PaymentsBySelectionCriteria().ConvertToCriteria(report);
convertedReport.PathToProjectFile = reportPath;
var path = Path.GetDirectoryName(env.WebRootPath) + "\\pdfs\\" + Guid.NewGuid() + ".pdf";
var csvPath = Path.GetDirectoryName(env.WebRootPath) + "\\csvs\\" + Guid.NewGuid() + ".csv";
var reportModel = new ReportPaymentsBySelection();
if (convertedReport.CreateCSVFile == true)
{
convertedReport.CSVFileName = csvPath;
}
reportModel.CreateReportAsPDFOrAddToQueue(convertedReport, path, loggedInUserID, out Notification notification, out bool addedToQueue);
//Add the report to the process queue
if (addedToQueue == true)
{
return Json(new
{
success = false,
message = "The report has been added to the queue."
});
}
if (notification.HasErrors)
{
return Json(new
{
success = false,
message = notification.GetConcatenatedErrorMessage(Environment.NewLine + Environment.NewLine)
});
}
return Json(new
{
success = true,
warning = notification.HasWarnings,
message = notification.GetConcatenatedWarningMessage(Environment.NewLine + Environment.NewLine),
pdf = path,
csvCreated = convertedReport.CreateCSVFile,
csv = csvPath
});
}
I came up with my own solution for this by creating a new property to keep track of the index. I created some hidden inputs and added the class sort-index to each of them.
public class SortOrder
{
public string Name { get; set; }
public bool SortBy { get; set; }
public bool Subtotal { get; set; }
public bool NewPage { get; set; }
public int SortIndex { get; set; }
}
When the submit button is clicked, I update the hidden index inputs to re-order to the current position in the UI.
//Update the SortIndex value of each sort order option
$(".sort-index").each(function (i, el) {
//console.log("Index: " + i + ". Value: " + $(this).val());
//Set the value of the sort index input to the index
$(this).val(i);
});
you can do this in one method with Html Table
Create the same thing inside a table
Then allow user to drag and drop the list
finaly get the table rows as a list with the javascript
Above list will be in user arranged way, I will add an example code below
You sort this list as your wish and click the 'ClickMe' button
this code for your reference only,it is different from your code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Easy Drag and Drop HTML Table Rows With jQuery</title>
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="https://getbootstrap.com/docs/4.0/examples/starter-template/starter-template.css" rel="stylesheet">
</head>
<body>
<main role="main" class="container">
<table class="table table-striped table-hover" id="tbl">
<thead class="thead-dark">
<tr>
<th>Row</th>
<th>Name</th>
<th>ID Number</th>
<th>Location</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>01</td>
<td>Rahim Hawkins</td>
<td>1640060874099</td>
<td>Bursa</td>
<td>May 29, 2017</td>
</tr>
<tr>
<td>02</td>
<td>Carter James</td>
<td>1672062705399</td>
<td>Geer</td>
<td>Mar 30, 2019</td>
</tr>
<tr>
<td>03</td>
<td>Merritt Fernandez</td>
<td>1669120981299</td>
<td>Gooik</td>
<td>Jun 3, 2017</td>
</tr>
<tr>
<td>04</td>
<td>Ross Robbins</td>
<td>1640092139299</td>
<td>Lint</td>
<td>Mar 22, 2018</td>
</tr>
<tr>
<td>05</td>
<td>Allistair Warren</td>
<td>1690102625999</td>
<td>Bicester</td>
<td>Dec 22, 2017</td>
</tr>
<tr>
<td>06</td>
<td>Yoshio Finch</td>
<td>1643051322099</td>
<td>Baulers</td>
<td>Sep 15, 2018</td>
</tr>
<tr>
<td>07</td>
<td>Wylie Holland</td>
<td>1662122249099</td>
<td>Penicuik</td>
<td>Apr 22, 2018</td>
</tr>
<tr>
<td>08</td>
<td>Maxwell Lindsay</td>
<td>1637021237499</td>
<td>St. John's</td>
<td>Nov 30, 2018</td>
</tr>
<tr>
<td>09</td>
<td>Orson Schneider</td>
<td>1610061567599</td>
<td>Gresham</td>
<td>Mar 7, 2018</td>
</tr>
<tr>
<td>10</td>
<td>Ahmed Puckett</td>
<td>1626021923499</td>
<td>Valbrevenna</td>
<td>Jul 20, 2018</td>
</tr>
</tbody>
</table>
<button onclick="fun()">ClickMe</button>
</main><!-- /.container -->
<!-- Bootstrap & Core Scripts -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<script src="https://getbootstrap.com/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$('tbody').sortable();
function fun(){
var table = document.getElementById("tbl");
var noOfrows=table.rows.length;
var res = new Array(noOfrows);
for (var i=0;i<noOfrows;i++){
res[i]=table.rows[i].cells[0].innerHTML;
}
alert(res);
}
</script>
</body>
</html>
I have a controller where i call a page with a data model.
//** Get all members
IEnumerable<mdMedlemmer> medlemsModels = _medlemmer.GetAll(_options.LoggedInGuid.ToString());
//** Get listing result
var ListingResult = medlemsModels.Select(result => new MedlemsIndexListingModel
{
Id = result.ID,
Navn = result.Navn,
LicensNummer = result.LicensNummer,
Niveau = result.Niveau
}).OrderBy(o => o.Navn);
//** Set model
var model = new MedlemsIndexModel
{
Medlems = ListingResult
};
//** Show view with model
return View(model);
In my cshtml page i have this code:
#model MinDartklub.Models.Medlemmer.MedlemsIndexModel
<table class="table table-condensed" id="medlemsIndexTable">
<thead>
<tr>
<th>Navn</th>
<th>Vælg</th>
</tr>
</thead>
<tbody>
#using (Html.BeginForm("Pujle", "Turnering", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
int counter = 1;
#foreach (var medlems in Model.Medlems)
{
<tr class="medlemsRow">
<td class=""><input type="text" navn="txtSpiller_#counter" id="txtSpiller_#counter" value="#medlems.Navn" disabled/></td>
<td class=""><input type="checkbox" name="cbSpiller_#counter" /></td>
</tr>
counter++;
}
<tr class="medlemsRow">
<td class="" colspan="2"><input class="btn btn-lg btn-info" type="submit" value="Start pulje" /></td>
</tr>
}
</tbody>
</table>
Back in the controller i try to read the data:
[HttpPost]
public ActionResult Pujle(string txtSpiller_1, string cbSpiller_1)
{
return RedirectToAction("Index", "Turnering");
}
The cshtml pagge shows all the members and a checkbox
In the controller Start() method I want to read all the members who have been checked.
Any idea on how I do that?
I found out I could use Request.Form.ToList()
This gives me a list of the member where I clicked in the checkbox.
I create a filter on a table. Here the code:
<table id="tableText" class="table table-hover table-striped" ng-init="allNews()">
<tr>
<td colspan="5">
<input type="text" placeholder="Ricerca testo" class="form-control" ng-model="inputText">
</td>
</tr>
<tr>
<th>Titolo</th>
<th>Text</th>
<th>Disattivato</th>
<th>Modifica</th>
<th ng-if="!cancelDelete">Elimina</th>
<th ng-if="cancelDelete">Annulla</th>
</tr>
<tr ng-repeat="news in allNews | filter : inputText">
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteTitle"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.title" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteText"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.arg" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><input type="checkbox" disabled ng-model="news.isDeleted"></div>
<div ng-show="editingData[news.id]"><input type="checkbox" ng-model="news.isDeleted"></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="modify" class="btn btn-primary" ng-click="modify(news, $event)">Modifica</button></div>
<div ng-show="editingData[news.id]"><button id="accept" class="btn btn-success" ng-click="update(news)">Accetta</button></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="delete" class="btn btn-danger" ng-click="delete(news.id)">Cancella</button></div>
<div ng-show="editingData[news.id]"><button id="cancel" class="btn btn-danger" ng-click="cancelModify()">Annulla</button></div>
</td>
</tr>
</table>
The entry on the table is read from db:
$scope.allNews = function () {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
I'd like to highlight the text that is search in the 1st row of the table. For now, i receive this error:
angular.js:13920 Error: [filter:notarray] Expected array but received: function ()
but the filter works.
Your problem is that $scope.allNews is a function. When you use it in ng-repeat directive and the directive is evaluated for the first time, your angular will try to examine the allNews property of your $scope as an array.
When the function gets called the first time (which might never happen when angular first encouters the error), it woul overwrite the allNews property with the resulting array of your $http POST request.
Rename either the function or the property and bind your ng-repeat to the array it recieves (and maybe initialize it with an empty array until it is populated by the $http result).
Something like:
$scope.allNews = [];
$scope.getAllNews = function() {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
Alternatively try using ngResource, create a service and inject that into your controller. Then populate the array by accessing the service.
So far I've been successful in creating a function that removes an element from ng-repeat and to toggle a form. I can't figure out how to edit a given element in that ng-repeat.
Ideally, I'd like to click on the element, and have the form show with the existing values already in the input. So that all the user needs to do is edit whichever fields desired, click submit and that newly updated item is then added back to the array where it originally was.
This is what I've come up with:
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
<input type="text" />
<input type="text" />
<button ng-click="vm.update()">Submit</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list">
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm()">E</span>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
and:
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function() {
vm.showEditForm = !vm.showEditForm;
};
vm.update = function() {
// ???
}
}
function testSrvc() {
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function() {
this.list.splice() //???
}
}
You need to tell which item you want to edit. So it should be
<span ng-click="vm.edit(item)">E</span>
Then this function should store a copy of that item to edit in some variable:
vm.edit= function(item) {
vm.editedItem = angular.copy(item);
};
And the form should be bound to this item copy:
<input type="text" ng-model="vm.editedItem.name"/>
<input type="text" ng-model="vm.editedItem.desc"/>
Then the save method should find back the original item in the array (thanks to its ID or index), and copy the edited fields from vm.editedItem.
angular
.module('testApp', [])
.controller('testCtrl', testCtrl)
.service('testSrvc', testSrvc);
function testCtrl(testSrvc) {
var vm = this;
vm.list = testSrvc.list;
this.index1 = -1;
vm.removeItem = function(idx) {
testSrvc.remove(idx);
}
vm.showEditForm = false;
vm.toggleEditForm = function(item,index) {
this.show = true;
this.index1 = index;
};
vm.update = function(item,index) {
vm.list[index].name = item.name;
vm.list[index].desc = item.desc;
this.index1 = -1;
}
}
function testSrvc() {
this.show = false;
this.list = [
{
name: 'asdf',
desc: 'lorem ipsum dolor'
},
{
name: 'qwerty',
desc: 'lorem ipsum amet'
}
];
this.remove = function(itemIndex) {
this.list.splice(itemIndex, 1);
};
this.edit = function(index) {
this.show = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
<div ng-controller="testCtrl as vm">
<form ng-show="vm.showEditForm">
</form>
<table>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
<tr ng-repeat="item in vm.list" >
<td>
{{item.name}}
</td>
<td>
{{item.desc}}
<span ng-click="vm.toggleEditForm(item,$index)">E</span>
<input ng-show="vm.index1 == $index" type="text" ng-model="item.name" />
<input ng-show="vm.index1 == $index" type="text" ng-model="item.desc" />
<button ng-show="vm.index1 == $index" ng-click="vm.update(item,$index)">Submit</button>
<span ng-click="vm.removeItem($index)">X</span>
</td>
</tr>
</table>
</div>
</div>
This is my Script for "Onchange" event for dropdown
<script src="~/Scripts/jquery-1.7.1.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$("#PId").change(function () {
alert("Change Event");
#foreach (var item in Model)
{
var pid = item.PId.ToString();
var id = Request["PId"];
if(pid == id)
{
var email = item.PEmail;
var phn1 = item.Phn1;
var gender = item.Gender;
}
}
alert("123");
alert($("#PEmail", "#Phn1", "#Gender", $(this)).show());
});
});
</script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>PatientMaster</legend>
<table>
<tr>
<td> #Html.Label("PName") </td>
<td> #Html.DropDownList("PId", #ViewBag.PId as SelectList, "---Select---", new { onchange = "PId" }) </td>
</tr>
<tr>
<td> #Html.Label("PAdd") </td>
<td> #Html.TextBox("PAdd") </td>
<td> #Html.Label("PCity") </td>
<td> #Html.TextBox("PCity") </td>
</tr>
<tr>
<td> #Html.Label("Gender") </td>
<td> #*<input id="gender" name="gender"/>*#
#Html.TextBox("Gender")
</td>
</tr>
<tr>
<td> #Html.Label("DOB") </td>
<td> #Html.Editor("DOB") </td>
<td> #Html.Label("PEmail") </td>
<td> #*<input id="PEmail" type="text" />*#
#Html.TextBox("PEmail") </td>
</tr>
<tr>
<td> #Html.Label("Phn1") </td>
<td> #*<input id="phn1" type="text" />*#
#Html.TextBox("Phn1") </td>
<td> #Html.Label("Phn2") </td>
<td> #Html.TextBox("Phn2") </td>
</tr>
<tr>
<td> #Html.Label("PStatus") </td>
<td> #Html.DropDownList("Status")
</td>
<td> #Html.Label("RefNo") </td>
<td> #Html.TextBox("RefNo")</td>
</tr>
<tr>
<td> #Html.Label("Pswd") </td>
<td> #Html.TextBox("Pswd") </td>
</tr>
</table>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
How to display email, phn and gender of person in textbox from database to update the values. I have used "ViewBag" to display dropdown. what value should I pass in CSHTML code in "#Html.DisplayFor"
This is my controller code for get method:
//Get
public ActionResult Update()
{
PatientMaster pm = new PatientMaster();
List<PatientMaster> Patient = new List<PatientMaster>();
using (GPediaEntities gp = new GPediaEntities())
{
Patient = gp.PatientMasters.OrderBy(a => a.PId).Distinct().ToList();
}
ViewBag.PId = new SelectList(Patient, "PId", "PName").Distinct().ToList();
foreach (var item in Patient)
{
if (item.PId.ToString() == Request["PId"])
{
string email = item.PEmail;
string gender = item.Gender;
string phn1 = item.Phn1;
}
}
List<SelectListItem> status = new List<SelectListItem>();
status.Add(new SelectListItem { Text = "Existing Patient", Value = "Existing" });
status.Add(new SelectListItem { Text = "New Patient", Value = "New" });
ViewBag.Status = new SelectList(status, "Value", "Text", "Existing Patient");
if (pm.PId.Equals(Request.Params["PId"]))
{
pm.PName = pm.PName;
pm.Gender = pm.Gender;
pm.PEmail = pm.PEmail;
pm.Phn1 = pm.Phn1;
}
return Json(pm.PEmail);
}
//Post
[HttpPost]
public ActionResult Update(PatientMaster pm)
{
List<PatientMaster> Patient = new List<PatientMaster>();
using (GPediaEntities gp = new GPediaEntities())
{
Patient = gp.PatientMasters.OrderBy(a => a.PId).Distinct().ToList();
}
ViewBag.PId = new SelectList(Patient, "PId", "PName").Distinct();
pm.PName = pm.PId.ToString();
if (ModelState.IsValid)
{
using (GPediaEntities gp = new GPediaEntities())
{
db.PatientMasters.Add(pm);
db.SaveChanges();
pm = null;
}
}
return View(pm);
}
Thanx in advance
Try Request.Params["paramName"]