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.
Related
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 !
I created view where i listed my all records and i wanted to delete particular record after click on delete Button . But my record is deleted.
Following is the code-
Controller code-
public ActionResult Faqdelete()
{
var res = dbobj.tbl_FAQ.ToList();
return View(res);
}
[HttpPost]
public ActionResult Faqdelete(int id)
{
var res = dbobj.tbl_FAQ.Where(x => x.FAQ_ID == id).FirstOrDefault();
dbobj.tbl_FAQ.Remove(res);
dbobj.SaveChanges();
var Faqdata = dbobj.tbl_FAQ.ToList();
return View("Faqdelete",Faqdata);
}
- View page Code-
#model IEnumerable<ClassOne_SampleProject.Models.tbl_FAQ>
#{
ViewBag.Title = "Faqdelete";
}
<h2>Faqdelete</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.FAQ_Question_Answer)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.Raw(item.FAQ_Question_Answer)
</td>
<td>
Delete
</td>
</tr>
}
</table>
Please tell me where exactly the problem.
Modify your anchor tag as
<td>
<a href="Url.Action("Faqdelete", "somecontroller", new { id = item.FAQ_ID })"
class="btn btn-danger">Delete</a>
</td>
I have a HTML table as below in my View:
<table id="tblCurrentYear">
<tr>
<td>Leave Type</td>
<td>Leave Taken</td>
<td>Leave Balance</td>
<td>Leave Total</td>
</tr>
#foreach (var item in Model.LeaveDetailsList)
{
<tr>
<td>#Html.TextBoxFor(m => item.LeaveType, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTaken, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveBalance, new { width = "100" })</td>
<td>#Html.TextBoxFor(m => item.LeaveTotal, new { width = "100" })</td>
</tr>
}
</table>
I want to iterate through all the html table rows and insert the values in ADO.NET DataTable.
Simple speaking, converting HTML Table to ADO.NET DataTable.
How to extract values from HTML Table and insert into ADO.NET DataTable?
The view is based on the following model
public class LeaveBalanceViewModel
{
public LeaveBalanceViewModel()
{
this.EmployeeDetail = new EmployeeDetails();
this.LeaveBalanceDetail = new LeaveBalanceDetails();
this.LeaveDetailsList = new List<LeaveBalanceDetails>();
}
public EmployeeDetails EmployeeDetail { get; set; }
public LeaveBalanceDetails LeaveBalanceDetail { get; set; }
public List<LeaveBalanceDetails> LeaveDetailsList { get; set; }
}
In order to bind to a model on post back, the name attributes of the form controls must match the model properties. Your use of a foreach loop does not generate the correct name attributes. If you inspect the html you will see multiple instances of
<input type="text" name="item.LeaveType" .../>
but in order to bind to your model the controls would need to be
<input type="text" name="LeaveDetailsList[0].LeaveType" .../>
<input type="text" name="LeaveDetailsList[1].LeaveType" .../>
etc. The easiest way to think about this is to consider how you would access the value of a LeaveType property in C# code
var model = new LeaveBalanceViewModel();
// add some LeaveBalanceDetails instances to the LeaveDetailsList property, then access a value
var leaveType = model.LeaveDetailsList[0].LeaveType;
Since your POST method will have a parameter name (say model), just drop the prefix (model) and that's how the name attribute of the control must be. In order to do that you must use either a for loop (the collection must implement IList<T>)
for(int i = 0; i < Model.LeaveDetailsList.Count; i++)
{
#Html.TextBoxFor(m => m.LeaveDetailsList[i].LeaveType)
....
}
or use a custom EditorTemplate (the collection need only implement IEnumerable<T>)
In /Views/Shared/EditorTemplates/LeaveBalanceDetails.cshtml
#model yourAssembly.LeaveBalanceDetails
<tr>
<td>#Html.TextBoxFor(m => m.LeaveType)</td>
....
</tr>
and then in the main view (not in a loop)
<table>
.... // add headings (preferably in a thead element
<tbody>
#Html.EditorFor(m => m.LeaveDetailsList)
</tbody>
</table>
and finally, in the controller
public ActionResult Edit(LeaveBalanceViewModel model)
{
// iterate over model.LeaveDetailsList and save the items
}
With respect to your requirement, try this
jQuery(document).on("change", ".DDLChoices", function (e) {
var comma_ChoiceIds = '';
var comma_ChoicesText = '';
$('input[class="DDLChoices"]').each(function (e) {
if (this.checked) {
comma_ChoiceIds = comma_ChoiceIds + $(this).val() + ',';
comma_ChoicesText = comma_ChoicesText + $(this).parent('label').parent() + ',';
}
});
$('#ChoiceIds').val(comma_ChoiceIds);
$('#ChoiceText').val(comma_ChoicesText);
});
#using (Html.BeginForm("Actionname", "Controllername", FormMethod.Post, new { id = "frmChoices" }))
{
#Html.HiddenFor(m => m.ChoiceText, new { #id = "ChoiceText" })
#Html.HiddenFor(m => m.ChoiceIds, new { #id = "ChoiceIds" })
<div class="form-group">
<div>
<table>
<tr>
<th>Name</th>
<th>Selected</th>
</tr>
#foreach (var item in #Model.Choices)
{
<tr>
<td> <label>#item.ChoicesText</label> </td>
<td> <input class="DDLChoices" value="#item.ChoiceIds" type="checkbox" /></td>
</tr>
}
</table>
</div>
<input type="button" value="Submit" onclick="return ChoicesPoster.passChoices()"
</div>
}
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.
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"]