Add items to an existing list mvc5 - list

(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.
This is my request for the projects :
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
ViewBag.ProjectTimeSHeet = projectAssignment;
This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"
And this is my code of my dropdown:
<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
'<option value="">----Select----</option>#Html.Raw(projsStr)</select>';
SOLUTION:
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
});
ViewBag.ProjectTimeSHeet = projectAssignments;
And the result:

Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).
As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:
ViewBag.ProjectTimeSHeet = projectAssignment
.Concat(new[]
{
new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
},
new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
},
new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
},
});

var myOptions = {
val1 : 'Vacancy',
val2 : 'Unplanned Absence',
val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
through Javascript
var ddl = document.getElementById("dropdownID");
for ( let key in myOptions )
{
var option = document.createElement("OPTION");
option.innerHTML = key
option.value = myOptions[key]
ddl.options.add(option);
}

Related

Linq query with group by with .NET Core

I'm trying to do a simple query. I want to have a list with a string and a Guid and a sub-list with a decimal and a string. I have my query this way but it keeps getting error when translated to Entity Framework what am I doing wrong?
Thanks in advance
var a = ( from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString ,
DecimalValue = icc.DecimalValue
}).GroupBy(x => new { x.GuidId , x.StringN }).
Select(x => new Model
{
GuidId = x.Key.GuidId ,
StringN = x.Key.StringN ,
Values= x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
})
}
).OrderBy(x => x.StringN );
Error:
The LINQ expression '(GroupByShaperExpression:
KeySelector: new {
GuidId = (p.Id),
StringN = (p.Name)
},
ElementSelector:new {
GuidId = (ProjectionBindingExpression: GuidId ),
StringN = (ProjectionBindingExpression: StringN ),
CCString = (ProjectionBindingExpression: CCString ),
DecimalValue = (ProjectionBindingExpression: DecimalValue )
}
)
.Select(y => new OtherModel{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
}
)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
It is SQL limitation. You cannot select grouped items, only Key and aggregation result is allowed.
Add AsEnumerable to your LINQ query to do grouping on the client side:
var a = (
from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString,
DecimalValue = icc.DecimalValue
})
.AsEnumerable()
.GroupBy(x => new { x.GuidId , x.StringN })
.Select(x => new Model
{
GuidId = x.Key.GuidId,
StringN = x.Key.StringN,
Values = x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue,
CCString = y.CCString
})
})
.OrderBy(x => x.StringN);

Search Marker Leaflet Map

I am working on an application with Django. There in this application, I am first using Django to create a database with points and extract a JSON file (It is called "markers.json"). Then, using this JSON file, I am creating markers on a map with Leaflet. When I finished entering all the points to the database they will be around 5000 thousand. So, I decided that it is a good idea to be able to search this markers with an input tag and a search button. I enter the "site_name" as input and when I click the "search" button the related marker should popup. However, always the same marker pops up and I don't know where I am doing wrong.
Could you please help me on that?
HTML PART
<input type="text" id="mast_find" name="mastName" placeholder="Search or masts...">
<button type="submit" id="mast_button">Search</button>
JAVASCRIPT PART
var streets = L.tileLayer( 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap',
subdomains: ['a', 'b', 'c']
}),
esri = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
}),
topo = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
attribution: 'Map data: © OpenStreetMap, SRTM | Map style: © OpenTopoMap (CC-BY-SA)'
});
var map = L.map( 'map', {
center: [20.0, 5.0],
minZoom: 2,
zoom: 2,
layers: [streets, esri, topo]
})
var baseMaps = {
"Streets": streets,
"Esri": esri,
"Topo": topo
};
$('.leaflet-control-attribution').hide()
L.control.scale().addTo(map);
L.control.layers(baseMaps).addTo(map);
var myURL = jQuery( 'script[src$="leaf.js"]' ).attr( 'src' ).replace( 'leaf.js', '' )
var myIcon = L.icon({
iconUrl: myURL + '/images/pin24.png',
iconRetinaUrl: myURL + '/images/pin48.png',
iconSize: [29, 24],
iconAnchor: [9, 21],
popupAnchor: [0, -14]
})
for ( var i=0; i < markers.length; ++i )
{
var deneme = [];
var meleme = L.marker( [markers[i].fields.latitude, markers[i].fields.longitude], {icon: myIcon} )
.bindPopup( "<b>" + "Mast name: " + "</b>" + markers[i].fields.site_name + "<b>" + "<br>" + "A: " + "</b>" + markers[i].fields.a_measured_height_lt + "<br>" + "<b>" + "k: " + "</b>" + markers[i].fields.k_measured_height_lt )
.addTo( map );
deneme.push(meleme);
document.getElementById("mast_button").onclick = mastFunct;
function mastFunct(){
var data = document.getElementById("mast_find");
for (var i=0; i < markers.length; ++i ){
var markerID = markers[i].fields.site_name;
if (markerID = data.value){
deneme[i].openPopup()
}
}
};
if (markerID = data.value){
should be
if (markerID == data.value){
the only issue that i see is this with the if (markerID = data.value){.
But you can try this alternative:
instead your for-loop:
map.eachLayer(function(marker){
if(marker.options){
var markerID = marker.options.site_name;
if (markerID == data.value){
marker.openPopup();
}
}
});
and add this to your marker creation:
L.marker([51.493782, -0.089951],{icon: myIcon, site_name: 'test'}).addTo(map)

How to do a MaxBy in RavenDb MapReduce

Using the Northwind database from RavenDB tutorial I'm trying to group orders by employee and get the most resent order for every employee.
Map:
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
Reduce with nonexisting MaxBy:
from result in results
group result by result.Employee into grp
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = grp.Max(result => result.MostRecent),
MostRecentOrderId = grp.MaxBy(result => result.MostRecent).MostRecentOrderId,
}
Reduce attempt:
from result in results
group result by result.Employee into grp
let TempMostRecent = grp.Max(result => result.MostRecent)
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = TempMostRecent,
MostRecentOrderId = grp.First(result => result.MostRecent == TempMostRecent).MostRecentOrderId
}
However my reduce attempt returns 0 results.
Also: will RavenDB treat the Order.OrderetAt as a proper DateTime value and order them correctly?
You need to do it like
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
from result in results
group result by result.Employee into grp
let maxOrder = grp.OrderByDescending(x=>x.MostRecent).First()
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = maxOrder.MostRecent,
MostRecentOrderId = maxOrder.MostRecentOrderId,
}

Google Visualization : How do I perform check/uncheck with google visualization table associated checkbox?

Problem:
I am unable to perform the check and uncheck action with google visualization table associated checkbox. The checkboxes are generated dynamically based on the query value.(0/1)
Code:
function drawQuestions(queryResponse, table_container_id) {
if (queryResponse.isError()) {
alert('Error in query: ' + queryResponseData.getMessage() + ' ' + queryResponseData.getDetailedMessage());
return;
}
var questionBankResponse = queryResponse.getDataTable();
if (questionBankResponse.getNumberOfRows() === 0) {
alert('Empty rows in query: ' + );
return;
}
var questionDataTable = new google.visualization.DataTable();
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
questionDataTable.addColumn('string', '');
var questionDataTableRow = new Array();
var rowCounter;
var questionHeader = questionBankResponse.getValue(0, 0);
for (rowCounter = 0; rowCounter < questionBankResponse.getNumberOfRows() ; rowCounter++) {
var count = 0 * 1;
var chbQuestion;
var questionId = questionBankResponse.getValue(rowCounter, 2);
var questionName = questionBankResponse.getValue(rowCounter, 3);
var answerValue = questionBankResponse.getValue(rowCounter, 4);
var answerOthers = questionBankResponse.getValue(rowCounter, 5);
if (answerValue === null)
answerValue = 0;
if (answerValue.toString() === "1") {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" checked=\"true\" />";
}
else {
chbQuestion = "<input type=\"checkbox\"" + " id=\"" + questionId + "\" />";
}
if (isNaN(answerOthers))
txtAnswerOthers = "<input type=\"text\"" + "size=\"100\" id=\"" + questionId + "\"" + " value='" + answerOthers + "' name='" + answerOthers + "' />";
else
txtAnswerOthers = null;
questionDataTableRow[count++] = chbQuestion;
questionDataTableRow[count++] = questionName;
questionDataTableRow[count++] = txtAnswerOthers;
questionDataTable.addRow(questionDataTableRow);
}
for (rowCounter = 0; rowCounter < questionDataTable.getNumberOfRows() ; rowCounter++) {
questionDataTable.setProperty(rowCounter, 0, "style", "width:30px");
questionDataTable.setProperty(rowCounter, 1, "style", "width:100%");
}
var tableObject = new google.visualization.Table(document.getElementById(table_container_id));
tableObject.draw(questionDataTable, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
Issue: Checkbox state has not been changed before and after the click.
Referred: Previous answer reference
Finally, I developed a solution for this. Here it is.
First, draw the table using google visualization API then draw the checkbox using HTML dom.
function handleQuestionsSqlQueryResponse(dataQueryQuestionsResponse) {
if (dataQueryQuestionsResponse.isError()) {
alert('Error in query: ' + dataQueryQuestionsResponse.getMessage() + ' ' + dataQueryQuestionsResponse.getDetailedMessage());
return;
}
var dtQuestions = dataQueryQuestionsResponse.getDataTable();
var intNoOfRows = dtQuestions.getNumberOfRows();
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var tblQuestions = new google.visualization.DataTable();
tblQuestions.addColumn('string', '');
tblQuestions.addColumn('string', '');
var arrQuestions = new Array();
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
if (strQuestionSection !== null && strQuestionDetails !== null) {
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var intCount = 0 * 1;
var tblQuestionsRow = new Array();
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
var strQuestionName = arrQuestions[intRowIterator].split("|")[1];
tblQuestionsRow[intCount++] = strQuestionName;
if (strQuestionName === "Other / Unknown? Please Describe:") {
tblQuestionsRow[intCount++] = "<input type=\"text\"" + "size=\"30\" id=\"" + strQuestionNo + "Others" + "\"" + " value='' name='" + strQuestionNo + "' disabled />";
} else {
tblQuestionsRow[intCount++] = null;
}
tblQuestions.addRow(tblQuestionsRow);
}
var tableObject = new google.visualization.Table(document.getElementById(strQuestionSection));
tableObject.draw(tblQuestions, { allowHtml: true, 'cssClassNames': cssClasses, width: '100%', sort: 'disable' });
}
}
for (intRowCounter = 0; intRowCounter < intNoOfRows ; intRowCounter++) {
var intQuestionValue = 0;
var strQuestionSection = dtQuestions.getValue(intRowCounter, 0);
var strQuestionDetails = dtQuestions.getValue(intRowCounter, 1);
var tblContainer = document.getElementById(strQuestionSection);
var tblReference = tblContainer.getElementsByTagName('TBODY')[0];
arrQuestions = strQuestionDetails.split(";");
for (var intRowIterator = 0; intRowIterator < arrQuestions.length; intRowIterator++) {
var tblRow = tblReference.rows[intRowIterator];
var tblCheckBox = tblRow.insertCell(0);
var strQuestionNo = arrQuestions[intRowIterator].split("|")[0];
if (strQuestionNo !== null) {
tblCheckBox.innerHTML = "<input type=\"checkbox\"" + " id=\"" + strQuestionNo + "\" name=\"" + strQuestionNo + "\" value=\"" +
intQuestionValue + "\" onchange=\"doCheckOrUnCheck('" + strQuestionNo + "');\" />";
}
}
}
}

Passing the lat, lng information to the google map script

I've have an index.html file that includes a gogglemap.js file to display a map of users location. Currently I am attempting to add the proper code to the index.html to pass the lat, lng info to the js file.
Here is filler content for the index file to show what I am attempting to do:
<h3><display user city></h3> <---- this needs to display users city and has filler text to show what I am trying to accomplish.
<div id="map"></div>
<script>var lat=12.356;var lng=-19.31;var country="User Country";var city="User City";</script> <----- seems like it is getting the lat/lng somehow before the index page loads and inserting this script into the index file?
Here is the js file code:
var styles = [{yourcustomstyle}]
var myLatlng = { lat: lat, lng: lng };
function initialize() {
var mapOptions = {
zoom: 12,
center: myLatlng,
styles: styles,
panControl: false,
zoomControl: false,
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false
};
var map = new google.maps.Map( document.getElementById('map'), mapOptions );
for (var a = 0; a < 6; a++) {
c = Math.random();
c = c * (0 == 1E6 * c % 2 ? 1 : -1);
d = Math.random()
d = d * (0 == 1E6 * d % 2 ? 1 : -1);
c = new google.maps.LatLng( lat + 0.08 * c + 0.052, lng + 0.2 * d + 0.08),
marker = new google.maps.Marker({
map: map,
position: c,
icon: 'marker.png'
});
}
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&callback=initialize';
document.body.appendChild( script );
}
window.onload = loadScript;