I have no idea how to work this out but my drop down list code looks as follows:
in the action:
DateTime[] allSundaysInMonth = GetDatesOfSundays(System.DateTime.Now);
DateTime[] allSundaysInLastMonth = GetDatesOfSundays(System.DateTime.Now.AddDays(-30));
List<SelectListItem> listOfSundays = new List<SelectListItem>();
foreach (DateTime dt in allSundaysInThisMonth)
{
listOfSundays.Add(new SelectListItem
{
Text = dt.Name,
Value = dt.Id.ToString(),
Selected = dt.CompanyId == Id
});
return listOfSundays;
}
I need to take the last two sundays af last month and all sundays of this month, but not future sundays, and build a list with all these sundays.
This is something i did while on a past project
public List<SelectListItem> CompanySelectList(List<Company> companyList, int selectedId = 0)
{
List<SelectListItem> listToReturn = new List<SelectListItem>();
foreach (Company c in companyList)
{
listToReturn.Add(new SelectListItem
{
Text = c.CompanyName,
Value = c.CompanyId.ToString(),
Selected = c.CompanyId == selectedId
});
}
return listToReturn;
}
just modify your T so it will return what you need.
You could look at the current date and start looping down, if the date then returned is a sunday set this value to be selected.
Related
I am trying set selected value to 2 List to show them on DropDownList in View.
I don't know why but StartDate also have EndDate selected value instead of the one I set it.
Controler
List<SelectListItem> StartDate = new List<SelectListItem>();
StartDate = lst;
if (StartDate.Count > 0)
{
StartDate[0].Selected = true;
System.Diagnostics.Debug.WriteLine("Start Date: " + StartDate[0].Text);
}
ViewBag.ListStartDate = StartDate;
//For EndDate, set "Select" for the last Entry
List<SelectListItem> EndDate = new List<SelectListItem>();
EndDate = lst; //lst is the default list without any select set to true
if (EndDate.Count > 0)
{
EndDate[EndDate.Count - 1].Selected = true;
System.Diagnostics.Debug.WriteLine("End Date: " + EndDate[EndDate.Count - 1].Text);
}
System.Diagnostics.Debug.WriteLine("[Finished End Info]");
ViewBag.ListEndDate = EndDate;
View
End Date
#Html.DropDownList("DateStartDropList", (List<SelectListItem>)ViewBag.ListStartDate)
Start Date
#Html.DropDownList("DateEndDropList", (List<SelectListItem>)ViewBag.ListEndDate);
StartDate = lst;
Please check the lst, I assume it should be a list of SelectListItem, right? If that is the case, the issue might relate that. Please refer the following sample:
If the lst is a list of SelectListItem, try to modify the code as below:
StartDate = lst.Select(c => new SelectListItem() { Value = c.Value, Text = c.Text, Selected = c.Selected }).ToList();
The updated code like this:
List<SelectListItem> lst = new List<SelectListItem>();
for (var i = 0; i < 10; i++)
{
var newdate = DateTime.Now.AddDays(i).ToString();
lst.Add(new SelectListItem() { Value = newdate, Text = newdate, Selected = false });
};
List<SelectListItem> StartDate = new List<SelectListItem>();
StartDate = lst.Select(c => new SelectListItem() { Value = c.Value, Text = c.Text, Selected = c.Selected }).ToList();
if (StartDate.Count > 0)
{
StartDate[0].Selected = true;
System.Diagnostics.Debug.WriteLine("Start Date: " + StartDate[0].Text);
}
ViewBag.ListStartDate = StartDate;
//For EndDate, set "Select" for the last Entry
List<SelectListItem> EndDate = new List<SelectListItem>();
EndDate = lst.Select(c => new SelectListItem() { Value = c.Value, Text = c.Text, Selected = c.Selected }).ToList(); //lst is the default list without any select set to true
if (EndDate.Count > 0)
{
EndDate[EndDate.Count - 1].Selected = true;
System.Diagnostics.Debug.WriteLine("End Date: " + EndDate[EndDate.Count - 1].Text);
}
System.Diagnostics.Debug.WriteLine("[Finished End Info]");
ViewBag.ListEndDate = EndDate;
Besides, you could also Create a DateModel, and use it to store the DropDownList select items, code as below:
public class DateModel
{
public string Value { get; set; }
public string Text { get; set; }
public bool IsSelected { get; set; }
}
Controller:
public IActionResult Index()
{
List<DateModel> lst = new List<DateModel>();
for(var i =0;i<10; i++)
{
var newdate = DateTime.Now.AddDays(i).ToString();
lst.Add(new DateModel() { Value = newdate, Text = newdate, IsSelected = false });
};
List<SelectListItem> StartDate = new List<SelectListItem>();
StartDate = lst.Select(c=> new SelectListItem() { Value = c.Value, Text = c.Text, Selected = c.IsSelected }).ToList();
if (StartDate.Count > 0)
{
StartDate[0].Selected = true;
System.Diagnostics.Debug.WriteLine("Start Date: " + StartDate[0].Text);
}
ViewBag.ListStartDate = StartDate;
//For EndDate, set "Select" for the last Entry
List<SelectListItem> EndDate = new List<SelectListItem>();
EndDate = lst.Select(c => new SelectListItem() { Value = c.Value, Text = c.Text, Selected = c.IsSelected }).ToList(); //lst is the default list without any select set to true
if (EndDate.Count > 0)
{
EndDate[EndDate.Count - 1].Selected = true;
System.Diagnostics.Debug.WriteLine("End Date: " + EndDate[EndDate.Count - 1].Text);
}
System.Diagnostics.Debug.WriteLine("[Finished End Info]");
ViewBag.ListEndDate = EndDate;
return View();
}
Then, the result as below:
I'm currently working on a web application that need to draw charts. For that, my controller sends some list in ViewBag and chart.js do the rest . But, for one View, I need to select all the consumption of a vehicle one by one. I don't know how to select each record , but I can select the sum of all of them.
My code for the sum is:
public ActionResult choice(string Snom , DateTime? date1 , DateTime? date2 ) // Snom is an input in an inputbox , to select a vehicle
{
var veh = from s in db.Fuel
select s;
var list = veh.ToList();
List<double?> repartitions = new List<double?>();
var comp = list.Where(x => x.VehicleId == Snom).Distinct(); // I select only the records for the selected vehicle
foreach (var item in comp)
{
repartitions.Add(list.Where(x => x.VehicleId == Snom).Sum(x => x.Volume)); // This is the line that i need to change
}
var rep = repartitions;
ViewBag.COMP = comp; // I place it in Viewbag
ViewBag.REP = repartitions.ToList();
return View();
}
How can I do that?
I know that I already posted a question like this but situation has changed and needed some changes.
Thanks!
EDIT
With the answer, I tried this code:
public ActionResult choice(string Snom , DateTime? date1 , DateTime? date2 ) // Snom is an input in an inputbox , to select a vehicle
{
var veh = from s in db.Fuel
select s;
var list = veh.ToList();
List<double?> repartitions = new List<double?>();
var comp = list.Where(x => x.VehicleId == Snom).Distinct(); // I select only the records for the selected vehicle
foreach (var item in comp)
{
repartitions.Add(list.FirstOrDefault(x => x.VehicleId == Snom).Volume); // This is the line that i need to change
}
var rep = repartitions;
ViewBag.COMP = comp;
ViewBag.REP = repartitions.ToList();
return View();
}
And it return the value of the first record, but not all the records.
Simple GroupBy should do the work :)
var grouped = list.GroupBy(v => v.Snom);
foreach(var group in grouped)
{
ViewBag.COMP = group.Key; // I place it in Viewbag
ViewBag.REP = group.Sum(v => v.Volume);
}
I got a list of DateTime which contains StartDate and EndDate,
User Should Select one or more TimeSpans from this list.
They are also have a structure class Named Courses.
How can I check if any overlaps is Happening or not
For example I got this
Start Date End Date
#1 7/20/2016 7/27/2016 Selected
#2 6/18/2016 7/25/2016 Selected
#3 7/20/2016 7/27/2016
#4 6/5/2016 6/10/2016
In this Example user has selected 2 dates that contains overlaps .
I want to warn the user with a message box or some Using C#.
Any opinion
Thanks
Ok, first created a class TimePeriod like this:
public class TimePeriod
{
public int Id;
public DateTime FromDate
{
get; set;
}
public DateTime ToDate
{
get; set;
}
public static DateTime Parse(string date)
{
var dt = DateTime.Parse(date,
CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.RoundtripKind);
return dt;
}
}
Then created a List with items of this class:
List<TimePeriod> list = new List<TimePeriod>();
Then added your examples of Dates (added all of them, for your need just add selected one's):
list.Add(new TimePeriod() { Id = 1, FromDate = TimePeriod.Parse("7/20/2016"), ToDate = TimePeriod.Parse("7/27/2016") });
list.Add(new TimePeriod() { Id = 2, FromDate = TimePeriod.Parse("6/18/2016"), ToDate = TimePeriod.Parse("7/25/2016") });
list.Add(new TimePeriod() { Id = 3, FromDate = TimePeriod.Parse("7/20/2016"), ToDate = TimePeriod.Parse("7/27/2016") });
list.Add(new TimePeriod() { Id = 4, FromDate = TimePeriod.Parse("6/5/2016"), ToDate = TimePeriod.Parse("6/10/2016") });
And last check with LINQ for overlapping:
var overlaps = from current in list
from compare in list
where
(
(compare.FromDate > current.FromDate &&
compare.FromDate < current.ToDate) ||
(compare.ToDate > current.FromDate &&
compare.ToDate < current.ToDate)
)
select new
{
Id1 = current.Id,
Id2 = compare.Id,
};
The result will be in this case 1/2 & 2/1 and 2/3 & 3/2. In your case it will be 1/2 & 2/1.
There is a very good library for working with time periods and their intersection on nuget.
Time Period Library
There is also an article on code project for it.
Time Period Library for .NET
You need to store which dates have been selected and if they occur in multiple selections right?
Store startedate and enddate of each selected timespan to a Tuple selectedTimeSpans
then:
List<int> useddays =new List<int>();
foreach (Tuple<DateTime, DateTime> selected in selectedTimeSpans)
{
DateTime start = selected.Value1;
DateTime end = selected.Value2;
DateTime current = start;
while(current <=end)
{
if(useddays.Contains((current-DateTime.MinValue).TotalDays)
MessageBox. Show("Already used!");
else
useddays.Add((current-DateTime.MinValue).TotalDays);
current.AddDays(1);
}
}
Thanks To all #c0d3b34n and #ThomasVoß ,
Also to this article https://stackoverflow.com/a/325964/3970128
This is All I Have Done
Ok, first created a class TimePeriod like this:
public class TimePeriod
{
public int Id;
public DateTime FromDate
{
get; set;
}
public DateTime ToDate
{
get; set;
}
public static DateTime Parse(string date)
{
var dt = DateTime.Parse(date,
CultureInfo.CreateSpecificCulture("en-US"), DateTimeStyles.RoundtripKind);
return dt;
}
}
Then created a List with items of this class:
List<TimePeriod> list = new List<TimePeriod>();
Then added your examples of Dates (added all of them, for your need just add selected one's):
list.Add(new TimePeriod() { Id = 1, FromDate = TimePeriod.Parse("7/20/2016"), ToDate = TimePeriod.Parse("7/27/2016") });
list.Add(new TimePeriod() { Id = 2, FromDate = TimePeriod.Parse("6/18/2016"), ToDate = TimePeriod.Parse("7/25/2016") });
list.Add(new TimePeriod() { Id = 3, FromDate = TimePeriod.Parse("7/20/2016"), ToDate = TimePeriod.Parse("7/27/2016") });
list.Add(new TimePeriod() { Id = 4, FromDate = TimePeriod.Parse("6/5/2016"), ToDate = TimePeriod.Parse("6/10/2016") });
Then
foreach (var variable in list)
{
foreach (var VARIABLE in list)
{
if (variable.Id == VARIABLE.Id)
{
continue;
}
if ((variable.FromDate <= VARIABLE.ToDate) && (variable.ToDate >= VARIABLE.FromDate))
{
Console.WriteLine("Problem Hapendes!! {0} <= {1} , {2} >= {3}", variable.FromDate.ToString(), VARIABLE.ToDate.ToString(), VARIABLE.ToDate.ToString(), VARIABLE.FromDate.ToString());
}
}
}
I am trying to add an item to an IEnumerable SelectList. I have an initial query that populates my list, I then have a query to check to see if an item called "INFORMATIONAL" exists. If not, I need to add it to the list returned from my initial query. Here is my code. It does not like list.Add(newItem). Any assistance would be appreciated. Thanks
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
IEnumerable<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
The problem is that your variable is of type IEnumerable<SelectListItem>. Either change it to List<SelectListItem> or use another variable.
public IEnumerable<SelectListItem> GetCategoriesByAccountID(string AccountID)
{
List<SelectListItem> list = null;
using (var context = new AMPEntities())
{
// Queries DB for list of categories by AccountID
var query = (from ca in context.CustomAlerts
where ca.AccountID == AccountID
orderby ca.AlertCategory
select new SelectListItem { Text = ca.AlertCategory, Value = ca.AlertCategory }).Distinct();
list = query.ToList();
// Checks list to see if "INFORMATIONAL" already exists
var item = (from l in list
where l.Value == "INFORMATIONAL"
select new SelectListItem { Text = l.Text, Value = l.Value }).FirstOrDefault();
// If "INFORMATIONAL" is not present add it to list
if (item == null)
{
var newItem = new SelectListItem { Text = "INFORMATIONAL", Value = "INFORMATIONAL" };
list.Add(newItem);
}
}
return list;
}
Essentially, you cannot, because IEnumerable does not necessarily represent a collection to which items can be added. See this question on SO.
How can I add an item to a IEnumerable<T> collection?
Here is something I came up with that might be helpful to someone. Maybe even me at a later date. Take a look at the last line of code.
CostCenterHeaders CostHeaders = CostCenterHeaders.GetCostCenterHeaders(ClientNumber);
List<SelectListItem> Level1Header = new List<SelectListItem>();
if (CostHeaders.Level1Heading !=null)
{
Level1Header.Add(new SelectListItem { Text = "All " + CostHeaders.Level1Heading + " Centers", Value = "" });
List<HierarchyLevel> HierarchyLevels = HierarchyLevel.GetHierarchyByLevel(ClientNumber);
Level1Header.AddRange(HierarchyLevels.Select(x => new SelectListItem() { Value = x.LevelID, Text = x.LevelDescr }).ToList());
}
I am using MVC4 to build up this project, and I'm having a bit of a hard time figuring out how to take the pre-populated html part that has a date of birth in it, and check it against the current days date to see if the person is above 18 or below 18. Depending on their age, i have a database that has a list of validation options for a drop down list that will display certain things depending on the age. If they are above 18, it will display 3 different results, if below 18, only 1 option will be available. I have tried a couple different ways, one of which worked fine by putting it in the View. But, I want to have this part running from the controller, I just want the logic separate from the ui. Here is the method that I'm working on for it, any help would be great! I've commented out an option or two that I've tried and hasn't worked.
public void SetupValidationList(DateTime? dateOfBirth = null)
{
var vtList = MetadataManager.GetValidationTypes().Where(x => x.DisplayInAdminTool).Select(x => x);
// populate drop down for Validation Method/TypeID
List<SelectListItem> items = vtList.Select(vtitem => new SelectListItem
{
Text = vtitem.DisplayName,
Value = vtitem.ID.ToString()
}).ToList();
items.Insert(0, new SelectListItem { Text = String.Empty, Value = String.Empty });
// If minor then only validation option is face to face minor
// If adult then remove face to face minor validation option
if (dateOfBirth.HasValue)
{
//List<SelectListItem> validationList = new List<SelectListItem>();
if (dateOfBirth >= DateTime.Now.AddYears(-18))
{
vtList(new SelectListItem { Text = "Patient Face to Face Minor" });
}
else
{
items.Add(new SelectListItem { Text = "Patient Face to Face" });
items.Add(new SelectListItem { Text = "Patient Phone" });
items.Add(new SelectListItem { Text = "Patient Notary" });
}
//if (Model.DateOfBirth >= DateTime.Now.AddYears(-18))
//{
// validationList.Add(allValidationList.FirstOrDefault(s => s.Text.Contains("Minor")));
//}
//else
//{
// validationList.AddRange(allValidationList.Where(s => !s.Text.Contains("Minor")));
//}
}
ViewData["ValidationList"] = items;
}
This should work to my mind.
public List<SelectListItem> GetSelectList(DateTime? dateOfBirth)
{
var vtList = MetadataManager.GetValidationTypes().Where(x => x.DisplayInAdminTool).Select(x => x);
List<SelectListItem> myList = new List<SelectListItem>();
var items = (from n in vtList
select new SelectListItem
{
Text = vtitem.DisplayName,
Value = vtitem.ID.ToString()
}).ToList();
foreach( var item in items)
myList.Add(item);
//I don't know, why you need this empty item:
myList.Add(new SelectListItem() { Text = String.Empty, Value = String.Empty });
if (dateOfBirth.HasValue)
{
if (dateOfBirth >= DateTime.Now.AddYears(-18))
{
myList.Add(new SelectListItem() { Text = "Patient Face to Face Minor" });
}
else
{
myList.Add(new SelectListItem() { Text = "Patient Face to Face" });
myList.Add(new SelectListItem() { Text = "Patient Phone" });
myList.Add(new SelectListItem() { Text = "Patient Notary" });
}
return myList; //or ViewBag.list = myList, if void()
}