How do I set the selected value on a select list.
For example, say i'm displaying an existing client and on the form it has a dropdown list for "Gender", I want "Male" to be selected (if that what was saved in the db) how do I do this?
When I'm building my model im doing something like
public ActionResult Edit(string id)
{
var client= _clientService.FindById(id);
var model = new ViewModels.Client()
{
GenderId= client.GenderId,
GenderList= CreateGenderList(GenderId)
};
}
private IEnumerable<SelectListItem> CreateGenderList(int gId)
{
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString() });
//Need to set the selected value, how?
return list.ToList();
}
Thank you in Advance.
You should make use of the additional SelectListItem.Selected property, and set this to true. For example:
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem {
Text = v.ToString(),
Value = ((int)v).ToString()});
var maleGenderItem = list.Single(x => x.Text == "Male");
maleGenderItem.Selected = true;
This did it
var list = Enum.GetValues(typeof(DomainObjects.Client.GenderList))
.Cast<DomainObjects.Client.GenderList>()
.Select(v => new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString(), Selected = gName.ToString() == ((int)v).ToString() });
return list.ToList();
Related
The below code is used to create a dropdown list of services that my company offers. The services are being pulled from our database and I hard coded and added an additional item named "SSN Trace" to the list. The problem is that the item is still showing up at the end of the list instead of falling in alphabetical order with the rest of the list items. Can anyone help?
public List<SelectListItem> createProductsDropdownForTransReport()
{
var resultsOfProductsSearch = findAllByEnumSet(EnumLookup.EnumSetType.SterlingWestProducts);
var transanctionsReportProducts = resultsOfProductsSearch
.Where(el => el.Ordinal != 95 && el.Ordinal != 253)
.Select(el => new SelectListItem { Text = el.Text, Value = el.Text })
.OrderBy(el => el.Text)
.ToList();
transanctionsReportProducts.Add(new SelectListItem { Text = "SSN Trace", Value = "SSN Trace" });
var allTransReportProductsOption = new SelectListItem
{
Text = "All",
Value = String.Join(" | ", transanctionsReportProducts.Select(x => x.Text))
};
transanctionsReportProducts.Insert(0, allTransReportProductsOption);
transanctionsReportProducts.OrderBy(el => el.Text);
return transanctionsReportProducts;
}
CORRECT CODE:
public IEnumerable<SelectListItem> createProductsDropdownForTransReport()
{
var resultsOfProductsSearch = findAllByEnumSet(EnumLookup.EnumSetType.SterlingWestProducts);
var transanctionsReportProducts = resultsOfProductsSearch
.Where(el => el.Ordinal != 95 && el.Ordinal != 253)
.Select(el => new SelectListItem { Text = el.Text, Value = el.Text }).ToList();
transanctionsReportProducts.Add(new SelectListItem { Text = "SSN Trace", Value = "SSN Trace" });
transanctionsReportProducts = transanctionsReportProducts.OrderBy(el => el.Text).ToList();
var allTransReportProductsOption = new SelectListItem
{
Text = "All",
Value = String.Join(" | ", transanctionsReportProducts.Select(x => x.Text))
};
transanctionsReportProducts.Insert(0, allTransReportProductsOption);
return transanctionsReportProducts;
}
You are not doing anything on the return by OrderBy. You can immediately return the result of the OrderBy. When you call OrderBy, it doesn't mutate the existing list that you passed in. It creates a new list of the ordered elements and you are not doing anything on it.
More information can be found here
public IEnumerable<SelectListItem> createProductsDropdownForTransReport()
{
var resultsOfProductsSearch = findAllByEnumSet(
EnumLookup.EnumSetType.SterlingWestProducts);
var transanctionsReportProducts = resultsOfProductsSearch
.Where(el => el.Ordinal != 95 && el.Ordinal != 253)
.Select(el => new SelectListItem { Text = el.Text, Value = el.Text })
.OrderBy(el => el.Text)
.ToList();
transanctionsReportProducts.Add(new SelectListItem {
Text = "SSN Trace", Value = "SSN Trace" });
var allTransReportProductsOption = new SelectListItem
{
Text = "All",
Value = String.Join(" | ", transanctionsReportProducts.Select(x => x.Text))
};
transanctionsReportProducts.Insert(0, allTransReportProductsOption);
return transanctionsReportProducts.OrderBy(el => el.Text);
}
New to C# and appreciate any help. The issue is that I need to filter the results of my api call against an array (using an "allowedA" and "allowedB" array.) I don't know how to edit the lambda expression to check against the loop.
var activities = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY);
var activityTypes = await _restClientTaxonomy.GetTaxonomyFullAsync(TAXONOMY_CLASSIFICATIONID_FOR_ACTIVITY_TYPES);
var documentEventxx = activities.Select(type => type.Id);
long [] allowedA = new long []{ 7137, 40385637};
long [] allowedB = new long []{ 7137, 40385637};
foreach (long value in documentEventxx)
{
foreach (var item in allowed)
{
if (item == value) {
//These are the values I am looking for -> values that are part of the documentEventxx and allowedB.
}
}
}
var result = activityTypes.Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
I have been reading about lambda expressions and foreach loops so please don't just post a random link.
Thanks in advance.
Filter the values before Selecting.
activityTypes.Where(x=>allowedA.Contains(x.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id && allowedB.Contains(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id,
Text = t.Name
}).ToList()
})
To filter you use .Where. You .Select to create a list of new types. So in order to filter, then create the lists of objects you want:
var result = activityTypes.Where(type=>isAllowed(type.Id)).Select(type => new CategoryViewModel
{
Id = type.Id,//This is where I want to add only items that are in the allowedA array
Text = type.Name,
Types = activities.Where(a => a.ParentId == type.Id&&isAllowed(a.Id)).Select(t => new TaxonomyMemberTextItem
{
Id = t.Id, //This is where I want to add only items that are in the allowedB array
Text = t.Name
}).ToList()
}).ToArray();
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());
}
in a mvc project i am using this method. However, when the database getting bigger and bigger, it is being very slow . How can i solve that ?
private List<SelectListItem> getDates() {
var db = new _Entities();
var list = new List<SelectListItem>();
var date = db.Location
.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.ToList();
//var date = db.Location.Select(m => m.DateService).Distinct();
foreach (var x in date)
{
list.Add(
new SelectListItem
{
Value = x.FirstOrDefault().DateServer.Date.ToShortDateString(),
Text = x.FirstOrDefault().DateServer.ToShortDateString()
} );
}
return list;
}
You should not create a list and a loop but use the database:
return db.Location.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.Select(group => new { group, first = group.First() })
.Select(x => new SelectListItem {
Value = x.first.DateServer.Date.ToShortDateString(),
Text = x.first.DateServer.ToShortDateString()
})
.ToList();
Since you are grouping by date the text and the value are the same, so it could be simplified:
return db.Location.GroupBy(k => EntityFunctions.TruncateTime(k.DateServer))
.Select(g => new SelectListItem { Value = g.Key.ToShortDateString(), Value = g.Key.ToShortDateString() })
.ToList();
I have 2 lists containing different types. One is a string[] and another is a List<SelectListItem>.
SelectListItem (it's in mvc):
public string Text {get;set;}
public string Value {get;set;}
public bool Selected {get;set;}
My string[] is just contains some text values.
What i'm trying to do is, get whatever is in the string[], then set "Selected = true" for whatever Value matches, and "Selected = false" for what doesnt match.
So lets say my string[] is:
Test1
Test2
Test3
And my List<SelectListItem> is:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = false },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = true }
In the above List<SelectListItem>, i have one match. So what i'd like to do, is set Selected = true for that particular entry so that i end up with:
new SelectListItem { Text = "Testing", Value = "Test1", Selected = true },
new SelectListItem { Text = "Testing", Value = "Test4", Selected = false }
How would I achieve this?
foreach(var i in selectListItemList)
i.Selected = stringArray.Contains(i.Value);
or using List.ForEach:
selectListItemList.ForEach(i => i.Selected = stringArray.Contains(i.Value));
How about
list.ForEach(x => x.Selected = stringarray.Contains(x.Value))
var items = SelectListItems.Where(p=>stringArray.Contains(p));;
foreach(var item in items)
item.Selected=true;