I am trying to search any employee status exist with IsProtected in the tabl empTable. if any row exist , then the variable ProtectedIsfound must be true
<table id="empTable" >
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
for (i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> // it is boolean in model
</tr>
}
</table>
<script>
var ProtectedIsfound = True // if any record exist with the value is Protected in the column status in the table empTable
</script>
I am trying to search any employee status exist with IsProtected in
the tabl empTable. if any row exist , then the variable
ProtectedIsfound must be true
Do you mean for each row, if the IsProtected is true, the ProtectedIsFound must be true? If that is the case, please refer to the following methods:
Using JavaScript or JQuery method: Loop through the table rows and cells and check if the IsProtected is true, then, based on the result to change the ProtectedIsFound value.
#*JQuery reference*#
<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript">
var ProtectedIsfound = false // default value.
//JavaScript method:
document.addEventListener("DOMContentLoaded", function (event) {
//loop through the tr and td, then based on the IsProtected value to change the ProtectedIsFound value.
var trlist = document.getElementById("empTable").getElementsByTagName("tr");
for (var i = 1; i < trlist.length; i++) {
if (trlist[i].getElementsByTagName("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
break;
}
}
console.log(ProtectedIsfound);
});
//JQuery script
$(function () {
$("#empTable").find("tr:not(:first-child)").each(function (index, item) {
if ($(item).find("td")[2].innerText.toLowerCase() == "true") {
ProtectedIsfound = true;
return false;
}
});
console.log(ProtectedIsfound);
});
</script>
Using Where and Select statement, code as below:
<script type="text/javascript">
var ProtectedIsfound = #Model.attendanceLogList.Where(c => c.IsProtected ==true).Select(c=>c).ToList().Count > 0 ? true : false;
console.log(ProtectedIsfound);
</script>
The Html page elements as below (Asp.net core Razor page application):
#page
#model RazorWebApplication5.Pages.HtmlTableModel
#{
}
<table id="empTable">
<tr>
<th>
Employee Name
</th>
<th>
Designation
</th>
<th>
Status
</th>
</tr>
#for (var i = 0; i < Model.attendanceLogList.Count; i++)
{
<tr>
<td>#Model.attendanceLogList[i].EmployeeName</td>
<td>#Model.attendanceLogList[i].Designation</td>
<td>#Model.attendanceLogList[i].IsProtected</td> #*// it is boolean in model*#
</tr>
}
</table>
.cshtml.cs file:
public class HtmlTableModel : PageModel
{
public List<AttendanceLog> attendanceLogList { get; set; }
public void OnGet()
{
//initial data
attendanceLogList = new List<AttendanceLog>()
{
new AttendanceLog(){ EmployeeName="Tom", Designation="A", IsProtected=false},
new AttendanceLog(){ EmployeeName="Jack", Designation="B", IsProtected=false},
new AttendanceLog(){ EmployeeName="Lucy", Designation="CC", IsProtected=true},
new AttendanceLog(){ EmployeeName="Daive", Designation="D", IsProtected=false},
new AttendanceLog(){ EmployeeName="Hanke", Designation="E", IsProtected=false}
};
}
}
public class AttendanceLog
{
public string EmployeeName { get; set; }
public string Designation { get; set; }
public bool IsProtected { get; set; }
}
Test result:
Change the for loop into:
"for (i = 0; i <= Model.attendanceLogList.Count; i++)", it should count up to the total number of the List.
Not sure what library you're using in the script, but instead of:
var ProtectedIsfound = True, it should state
You need a dedicated class name to the so you can refer it in the script
"bool ProtectedIsFound:"
It should be set to true by default.
foreach(emp in Model.attendanceLogList){
if (emp.IsProtected){
{here you will need to append the value in the Status column}
return true; }
else
return;
}
Related
I currently display each category individually, but I want to make it possible to view them all together.
Here in the screenshot, I show each category separately, but I want to add another All option that will show me all the animals in all the categories
My repository:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
var animal = _context.Animals
.Include(a => a.Category)
.Where(c => c.Category!.CategoryId == id);
return await animal.ToListAsync();
}
public DbSet<Category> GetCategories()
{
var category = _context.Categories;
return category;
}
My controller:
// Displays the animals by category using the Selectlist
public async Task<IActionResult> Commands(int id = 1)
{
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
My view:
#model IList<PetShop.Data.Models.Animal>
<label>Please select a category:</label>
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect"></select>
<table id="Table">
<thead>
<tr>
<th><label asp-for="#Model[0].PhotoUrl"></label></th>
<th><label asp-for="#Model[0].Name"></label></th>
<th><label asp-for="#Model[0].Category.Name"></label></th>
<th><label asp-for="#Model[0].Description"></label></th>
<th><label asp-for="#Model[0].BirthDate"></label></th>
<th>Edit Animal</th>
<th>Delete Animal</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model!) {
<tr>
<td><img src="~/Images/#item.PhotoUrl" id="ManagerImage"></td>
<td>#item.Name</td>
<td>#item.Category!.Name</td>
<td>#item.Description</td>
<td>#Html.DisplayFor(model => item.BirthDate)</td>
<td><a asp-action="EditAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Edit" id="DesignButton"></a></td>
<td><a asp-action="DeleteAnimal" asp-route-id="#item.AnimalId"><input type="submit" value="Delete" id="DesignButton"></a></td>
</tr>
}
</tbody>
</table>
image:
One way is that you can change your code in repository like below:
public async Task<IEnumerable<Animal>> SelectAnimalsById(int id)
{
List<Animal> data= new List<Animal>();
var animal = _context.Animal
.Include(a => a.Category);
if (id != 0)
{
data= await animal.Where(c => c.Category!.CategoryId == id).ToListAsync();
}
else
{
data= await animal.ToListAsync();
}
return data;
}
Another way is that you can change your action code like below:
public async Task<IActionResult> Commands(int id = 1)
{
//add this condition
//if id=0, return all the animals with all the categories
if(id==0)
{
return View(_context.Animal.Include(a => a.Category).ToList());
}
//keep the same.....
var petShopDbContext = await _animalRepository.SelectAnimalsById(id);;
ViewBag.Category = new SelectList(_catalogRepository.GetCategories(), "CategoryId", "Name", id);
return View(petShopDbContext);
}
Then change your view like below:
<select asp-items="ViewBag.Category" onchange="location.href='/Admin/Commands/'+this.value" id="DesignSelect">
<option value="0">ALL</option> //add this option
</select>
You could conditional add the where clause in your repository...
var animal = _context.Animals
.Include(a => a.Category);
if(id != 0)
{
animal.Where(c => c.Category!.CategoryId == id);
}
return await animal.ToListAsync();
Why in the view page, it shows all the rows "Not active currently" with this following code?
<td>
#{
if (item.LeadEngineers.All(n => n.Active == false))
{
#: Not active currently
}
var y = item.LeadEngineers.Where(n => n.Active == true).ToList();
if (y.Count() > 0)
{
#: Currently active
}
}
</td>
I want to check if the item's value in another table LeadEngineers is true or false, to show the item is currently active or not.
The item has many records in the table LeadEngineers, I want to check if all the records/rows have Active=False, then show "not active", if there's one row (at least one) has Active=true, then show "active now".
The definition of the item is in the view Model LeadIndexData:
public class LeadIndexData
{
//to show each item's full name
public IEnumerable<WebUser> WebUsers { get; set; }
//to show each item's assigned techniques
public IEnumerable<Technique> Techniques { get; set; }
//to show each item's supervised employees
public IEnumerable<EmployeeTech> EmployeeTechs { get; set; }
//to show if it's active or not
public IEnumerable<LeadEngineer> Leads { get; set; }
}
My Controller:
public ActionResult Index(int? id, int? techId)
{
var viewModel = new LeadIndexData();
var query = (from b in db.LeadEngineers
join a in db.WebUsers
on b.User_ID equals a.User_ID
where a.Active == true
select new
{
User_ID = b.User_ID,
User_FirstName = a.User_FirstName,
User_Surname = a.User_Surname
}).AsEnumerable().Select(x => new WebUser
{
User_ID = (int)x.User_ID,
User_FirstName = x.User_FirstName,
User_Surname = x.User_Surname
}).Distinct().ToList();
//put the query results into the list of leads
var engineers = query.AsEnumerable();
//use HashSet to hold a set of lead webusers
HashSet<WebUser> vme = new HashSet<WebUser>();
//access each item in the leads list and assign the lead webuser's details to each
foreach (var wu in engineers)
{
var w = new WebUser { User_ID = wu.User_ID, User_Surname = wu.User_FullName };
if (!(vme.Any(x => x.User_ID == wu.User_ID)))
{
vme.Add(w); //add the lead webuser details to the hashSet
}
}
//put the webusers details vme in the leadengineer viewmodel
viewModel.WebUsers = vme.ToList();
.....
}
My Index View page:
#model Version0.Models.LeadIndexData
....
....
#foreach (var item in Model.WebUsers)
{
string selectedRow = "";
if (item.User_ID == ViewBag.userId)
{
selectedRow = "success";
}
<tr class="#selectedRow" valign="top">
<td>
#Html.DisplayFor(modelItem => item.User_Surname)
</td>
<td>
#Html.DisplayFor(modelItem => item.User_FirstName)
</td>
<td>
#{
if (item.LeadEngineers.Any(n => n.Active == true))
{
#: Currently active
}
else
{
#: Not active currently
}
}
</td>
....
</table>
Here you are:
<td>
#{
if (item.LeadEngineers.Any(n => n.Active == true))
{
#: Currently active
}
else
{
#: Not active currently
}
}
</td>
I'm trying to add some data into page from database, after applying "filter"
After submit form, candidate list is update and I want to push this changes into page.
How can I do this in wicket ?
.java file
public class SearchCandidate extends WebPage {
private SearchCandidateModel searchCandidateModel = new SearchCandidateModel();
private List<CandidateEntity> candidate = new ArrayList();
public SearchCandidate(PageParameters p) {
super(p);
final TextField<String> firstName = new TextField<>("first_name", new PropertyModel<String>(searchCandidateModel, "firstName")); //Filter
final DataView dataView = new DataView("simple", new ListDataProvider(candidate)) {
public void populateItem(final Item item) {
final CandidateEntity user = (CandidateEntity) item.getModelObject();
item.add(new Label("firstName", user.getFirstName()));
}
};
Form<?> form = new Form<Void>("step1") {
#Override
protected void onSubmit() {
candidate = databse.findCandidate(searchCandidateModel.getFirstName());
//UPDATE TABLE
}
};
form.add(firstName);
add(form);
add(dataView);
}
}
html file:
<form wicket:id="step1">
<input wicket:id="first_name" type="text" size="30"/>
</form>
<table cellspacing="0" class="dataview">
<tbody>
<tr wicket:id="simple">
<td><span wicket:id="name">Test ID</span></td>
</tr>
</tbody>
</table>
You can make you DataProvider - dynamic:
new ListDataProvider() {
#Override protected List getData() {
if (noFilter) return emptyList
else return database.getList(filter)
}
}
This way the provider will always load the data according to your data filter.
For more information about static vs. dynamic models/providers check:
https://cwiki.apache.org/confluence/display/WICKET/Working+with+Wicket+models#WorkingwithWicketmodels-DynamicModels
After I have changed selected item in my DropDownList everything works fine. But the view doesnt show the newly selected item (value) in the view.
In my code there is #Model.Name What is wrong? I have already spent do many hours on this problem!
My controller looks like this:
//
// GET: /Province/
public ActionResult Test()
{
ModelState.Clear();
var items = _ProvinceService.GetAll();
ViewBag.Lista = new SelectList(items, "Id", "Name", -1);
var province = _LandskapService.FindByName("xyz");
return View("Test", province);
}
// POST /Province/Test
[HttpPost]
public ActionResult Test(int provinceId)
{
if (ModelState.IsValid)
{
ModelState.Clear();
var model = _ProvinceService.GetAll();
var province = _ProvinceService.FindById(provinceId);
ViewBag.Lista = new SelectList(model, "Id", "Name", province.Id);
return View("Test", province);
}
else
{
return View();
}
}
And here is the view:
#Html.DropDownList("dropDownList3", (SelectList)ViewBag.Lista, "-- select province", new { onchange = "UpdateProvince()" })
<table style="border-collapse:collapse">
<tr>
<th style="width:200px">Name</th>
</tr>
<tr>
<td> #Model.Name </td> Here is the problem: #Model.Name is correct but the view dont show it. Old value is displayed. But debugger shows right value (the selected value).
</tr>
function UpdateProvince() {
alert($('#dropDownList3').val());
var SelCat = $("#dropDownList3").val();
var text = $("#dropDownList3 option:selected").text();
var value = $("#dropDownList3 option:selected").val();
if (SelCat != 0) {
var url = '#Url.Action("Test", "Province")';
// $.get(url, {provinceId : value});
$.post(url, { provinceId: value });
}
}
I do have an Purchase request form, which dynamically creates row for ItemName, quantity, specification, unit of measurement.
I do have a one button called "Add item", which dynamically creates new rows.
When I submit this form how do I get it into Action class in Struts2.
JSP:
<table id="itemDetails" width="100%">
<tr width="100%" cellpadding="0" cellspacing="0" border="1" >
<th ><center>+</center></th>
<th >Item</th>
<th >Specification</th>
<th >Quantity</th>
<th >Unit Of Measurement</th>
<th >Operations</th>
</tr>
<s:iterator value="id" status="ctr" >
<tr>
<td width="5%"><input type="checkbox" name="rdel" ><br><br></td>
<td width="30%" ><input type="text" name="id[%{#ctr.index}].itemname" /></td>
<td width="30%"><input type="text" name="id[%{#ctr.index}].specification" ></td>
<td width="20%"><input type="text" name="id[%{#ctr.index}].quantity" ></td>
<td width="5%"><input type="text" name="id[%{#ctr.index}].uom" ></td>
<td width="10%"><a href="#" >Delete</a></td>
</tr>
</s:iterator>
</table>
Javascript for dynamic row creation:
<SCRIPT language="javascript">
function addRow(itemDetails) {
var table = document.getElementById(itemDetails);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var counts=rowCount-1;
var cell1 = row.insertCell(0);
var check = document.createElement("input");
check.type = "checkbox";
check.name="rdel";
cell1.appendChild(check);
var cell2 = row.insertCell(1);
var item = document.createElement("input");
item.type = "text";
item.name="id.item";
cell2.appendChild(item);
var cell3 = row.insertCell(2);
var specification = document.createElement("input");
specification.type = "text";
specification.name="id.specification";
cell3.appendChild(specification);
var cell4 = row.insertCell(3);
var quantity = document.createElement("input");
quantity.type = "text";
quantity.name="id.quantity";
cell4.appendChild(quantity);
var cell5 = row.insertCell(4);
var uom = document.createElement("input");
uom.type = "text";
uom.name="id.uom";
cell5.appendChild(uom);
var cell6 = row.insertCell(5);
var operations = document.createElement("a");
operations.setAttribute("href","#");
operations.innerText="Delete";
cell6.appendChild(operations);
}
</SCRIPT>
Action class method:
private List<ItemDetails> id;
public List<ItemDetails> getId(){
return this.id;
}
public void setId(List<ItemDetails> id) {
this.id = id;
}
public String savePurchaseRequest(){
try{
setId(getId());
for(ItemDetails itemdetails:id ) {
System.out.println( itemdetails.getItemname() + ":" + itemdetails.getSpecification() +":"+ itemdetails.getQuantity()+ ":"+ itemdetails.getUom() );
}
}catch(Exception e){
System.out.println("Exception:"+e);
}
return SUCCESS;
}
and ItemDetails class:
public class ItemDetails implements java.io.Serializable {
private String itemname;
private String specification;
private String quantity;
private String uom;
public ItemDetails() {
}
public ItemDetails(String itemname, String specification, String quantity, String uom) {
this.itemname = itemname;
this.specification = specification;
this.quantity = quantity;
this.uom = uom;
}
}
public String getItemname() {
return this.itemname;
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public String getSpecification() {
return this.specification;
}
public void setSpecification(String specification) {
this.specification = specification;
}
public String getQuantity() {
return this.quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getUom() {
return this.uom;
}
public void setUom(String uom) {
this.uom = uom;
}
}
you was almost there.
Just change the Javascript part where you assign the name attribute, including the index exactly as you do in the iteration:
item.name="id.item";
specification.name="id.specification";
// ecc...
must become
item.name="id["+counts+"].itemname";
specification.name="id["+counts+"].specification";
And you will be good.
It looks like you set your model items from another page. Try setting them to another variable than id, something like idOutput or so, I had problems myself before when trying to access a field via a getter when this field got set before, although I don't know why this was the case.
The model object (ItemDetails) needs public getters ( like getItemname() ) , so the JSP can read them.
You need to put correct names in the JavaScript, so that OGNL is able to handle them properly and apply values when you submit the form.
To submit newly added row you need to use only these names on the row you've being submitted.