How to select a text from selectlist? I want to auto select name "Dave" name from back-end on line First_Name_SELECT = "Dave";
<select asp-for="Person.First_Name" asp-items="#Model.First_Name_SELECT">
</select>
[BindProperty(SupportsGet = true)]
public string? First_Name { get; set; }
public SelectList? First_Name_SELECT { get; set; }
First_Name_SELECT = new SelectList(await _services.Get_Names());
First_Name_SELECT = "Dave";
public async Task<List<string>> Get_Names()
{
IQueryable<string> Query = (from m in _context2.Names_DbSet
select m.First_Names).Distinct().OrderBy(m => m);
return await Query.ToListAsync();
}
** UPDATE ** Following code works fine below but why First_Name_SELECT doesn't work? is this becuase I am using IQueryable?
[BindProperty(SupportsGet = true)]
public string? Last_Name { get; set; }
public SelectList? Last_Name_SELECT { get; set; }
Last_Name_SELECT = new SelectList(await _services.Get_LastNames());
var testing = Last_Name_SELECT .Where(x => x.Value.Contains("Name8")).FirstOrDefault();
testing.Selected = true;
public List<SelectListItem> Get_LastNames()
{
List<SelectListItem> Query = new List<SelectListItem>
{
new SelectListItem() { Selected =true, Value = "name1", Text = "name1" },
new SelectListItem() { Value = "name2", Text = "name2" },
new SelectListItem() { Value = "name3", Text = "name3" },
new SelectListItem() { Value = "name4", Text = "name4" },
new SelectListItem() { Value = "name5", Text = "name5" },
new SelectListItem() { Value = "name6", Text = "name6" },
new SelectListItem() { Value = "name7", Text = "name7" },
new SelectListItem() { Value = "name8", Text = "name8" },
new SelectListItem() { Value = "name9", Text = "name9" }
};
return Query;
}
If you have a model Person, you can try the below code:
var First_Name_SELECTSelectedValue = "Dave";
First_Name_SELECT = new SelectList(await _services.Get_Names(), First_Name_SELECTSelectedValue);
result:
You can read SelectList(IEnumerable, Object) to know more.
public SelectList (System.Collections.IEnumerable items, object
selectedValue);
Related
I have one master list of 2 filters and this linked with one app,
var filterData = new List<FilterData>
{
new FilterData { Filter1 = "test1", Filter2 = "X", GoesToApp = "App1"},
new FilterData { Filter1 = "test2", Filter2 = "X", GoesToApp = "App2"},
new FilterData { Filter1 = "test2", Filter2 = "Y", GoesToApp = "App1"},
new FilterData { Filter1 = "test3", Filter2 = "Y", GoesToApp = "App3"},
new FilterData { Filter1 = "test4", Filter2 = "Y", GoesToApp = "App3"},
new FilterData { Filter1 = "test1", Filter2 = "Z", GoesToApp = "App1"},
};
Now I have one Data which contains above filters data as well,
var data = new Data
{
Id = 1,
Filter2 = new List<string> { "X", "Y" },
FilterValues = new List<FilterValue>
{
new FilterValue {Filter1 = "test1", Value = "1"},
new FilterValue {Filter1 = "test2", Value = "2"},
new FilterValue {Filter1 = "test3", Value = "3"}
}
};
Here I need to filter Data with master list (above) on Filter1 and Filter2 and need to prepare data for each app (App1, App2 and so on).
With the code below I am able to prepare data for only one app at a time (example, App1) and this gives me the desired data what I want for this app based on comparing filters,
var destData = new Data()
{
Id = 1,
FilterValues = new List<FilterValue>()
};
var filter1DataForApp1 = filterData.Where(item =>
item.GoesToApp == "App1" && data.Filter2.Contains(item.Filter2))
.Select(item => item.Filter1);
foreach (var f1 in filter1DataForApp1)
{
destData.FilterValues.AddRange(data.FilterValues.Where(a => a.Filter1 == f1));
}
For a single item in Data if I have 50 apps , then above code I need to run 50 times for each app, which I want to avoid. How to do this? Is this possible to generates all apps data in one query?
Here are different class structures,
public class FilterData
{
public string Filter1 { get; set; }
public string Filter2 { get; set; }
public string GoesToApp { get; set; }
}
public class Data
{
public int Id { get; set; }
public List<string> Filter2 { get; set; }
public List<FilterValue> FilterValues { get; set; }
}
public class FilterValue
{
public string Filter1 { get; set; }
public string Value { get; set; }
}
Expected output data for,
App1 (only test1 and test2)
var app1Data = new Data
{
Id = 1,
Filter2 = null,
FilterValues = new List<FilterValue>
{
new FilterValue {Filter1 = "test1", Value = "1"},
new FilterValue {Filter1 = "test2", Value = "2"}
}
};
App2 (only test2)
var app1Data = new Data
{
Id = 1,
Filter2 = null,
FilterValues = new List<FilterValue>
{
new FilterValue {Filter1 = "test2", Value = "2"}
}
};
and so on...
I need one result something like something like List<GoesToApp, List<datafor that app>>
I think what you're looking for is something like this:
var result = filterData.GroupBy(x => x.GoesToApp).ToDictionary(grp => grp.Key, grp => {
return new Data
{
Id = 1,
FilterValues = grp.Where(item => data.Filter2.Contains(item.Filter2)).SelectMany(item => data.FilterValues.Where(f => item.Filter1 == f.Filter1)).ToList()
};
});
foreach(var item in result)
{
Console.WriteLine(item.Key);
foreach(var fv in item.Value.FilterValues)
Console.WriteLine($"\t{fv.Filter1}");
}
Live example: https://dotnetfiddle.net/xsomse
I have dropdownlist for country where it contains 6 countries. But I have a country table as well where I have more than 100 countries.
Now I want to check whether CountryId exists in dropdown list or not. If CountryId does not exists then by default choose first from dropdown list.
Any help is highly appreciated. Please show the way to do this?
Model
public int? Country { get; set; }
public IEnumerable<SelectListItem> CountriesList { get; set; }
Controller
var country = db.Country.SingleOrDefault(u => u.CountryId == user.CountryID)
int CountryId = countrylist.CountryId;
CountriesList = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "India" },
new SelectListItem { Value = "2", Text = "Pakistan" },
new SelectListItem { Value = "3", Text = "Nepal" },
new SelectListItem {Value = "4", Text = "Sri Lanka" },
new SelectListItem { Value = "5", Text = "Bangladesh" },
new SelectListItem {Value = "6", Text = "Bhutan" },
}
View
#Html.DropDownListFor(m => m.Country, Model.CountriesList, new { #class = "form-control" })
If you set the Country property value of your view model to the country id, the helper will select the corresponding option when the SELECT element is rendered.
You can check the specific countryId value exist in the CountriesList property of your view model using the Any method.
The SingleOrDefault method will return NULL when there are no records matching your where condition. So do a null check on that as well.
public ActionResult Create()
{
var vm = new CreateVm();
vm.CountriesList = new List<SelectListItem>
{
new SelectListItem { Value = "1", Text = "India" },
new SelectListItem { Value = "2", Text = "Pakistan" },
new SelectListItem { Value = "3", Text = "Nepal" },
new SelectListItem {Value = "4", Text = "Sri Lanka" },
new SelectListItem { Value = "5", Text = "Bangladesh" },
new SelectListItem {Value = "6", Text = "Bhutan" }
};
// user object is intstantiated somehave
var country = db.Country.SingleOrDefault(u => u.CountryId == user.CountryID);
if (country != null && vm.CountriesList
.Any(a => a.Value == country.CountryId.ToString()))
{
vm.Country = country.CountryId;
}
else
{
vm.Country = 1; // Value of "India" option (select list)item
}
return View(vm);
}
I'm trying to return a SelectList with <optgroup>'s using SelectListGroup, but the code below only returns the values in the SelectList without the groups. How can I have my select list separated by groups?
public SelectList MyList()
{
var group1 = new SelectListGroup() { Name = "Group 1" };
var group2 = new SelectListGroup() { Name = "Group 2" };
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = "1", Text = "Item 1", Group = group1 });
items.Add(new SelectListItem() { Value = "2", Text = "Item 2", Group = group2 });
return new SelectList(items, "Value", "Text");
}
I find this method works, which uses a strongly-typed approach:
View model:
public class PageViewModel
{
public int SelectedDropdownItem { get; set; }
public IEnumerable<SelectListItem> DropdownList { get; set; }
}
Example entity model (for this example):
public class Entity
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public bool IsDefault { get; set; }
}
Controller:
// Get list for the dropdown (this uses db values)
var entityList = db.Entity.ToList();
// Define the Groups
var group1 = new SelectListGroup { Name = "Active" };
var group2 = new SelectListGroup { Name = "Allowed" };
// Note - the -1 is needed at the end of this - pre-selected value is determined further down
// Note .OrderBy() determines the order in which the groups are displayed in the dropdown
var dropdownList = new SelectList(entityList.Select(item => new SelectListItem
{
Text = item.Name,
Value = item.Id,
// Assign the Group to the item by some appropriate selection method
Group = item.IsActive ? group1 : group2
}).OrderBy(a => a.Group.Name).ToList(), "Value", "Text", "Group.Name", -1);
// Assign values to ViewModel
var viewModel = new PageViewModel
{
// Assign the pre-selected dropdown value by appropriate selction method (if needed)
SelectedDropdownItem = entityList.FirstOrDefault(a => a.IsDefault).Id,
DropdownList = dropdownList
};
View:
<!-- If needed, change 'null' to "Please select item" -->
#Html.DropDownListFor(a => a.SelectedDropdownItem, Model.DropdownList, null, new { #class = "some-class" })
Hope it helps someone.
I'm receiving an error that a dropdownlist has invalid arguments. What's odd is that I have a similarly structured dropdownlist that is working fine, with no errors. The drop down with the error is the second one (that displays the year):
View:
#{
string month = "TempEmployments[" + idx + "].EmploymentStartMonth";
string year = "TempEmployments[" + idx + "].EmploymentStartYear";
}
#Html.DropDownList(month, (IEnumerable<SelectListItem>)this.ViewBag.MonthList,EmploymentStartMonth, new { #class = "field panel-field EmploymentDate", #id = month })
#Html.ValidationMessageFor(model => model.EmploymentStart)
#Html.DropDownList(year, (IEnumerable<SelectListItem>)this.ViewBag.YearList, EmploymentStartYear, new { #class = "field panel-field EmploymentDate", #id = year })
Controller:
[HttpPost]
public ActionResult AddEmploymentHistory(int ApplicantID, int RecordNum)
{
this.ViewBag.RecordNum = RecordNum;
this.ViewBag.StateList = this.GetStateList();
this.ViewBag.MonthList = this.GetMonthList();
this.ViewBag.YearList = this.GetYearList();
return PartialView("_EmploymentHistoryPartial");
}
private IEnumerable<SelectListItem> GetYearList()
{
List<SelectListItem> yearList = new List<SelectListItem>();
int current_yr = Convert.ToInt32(DateTime.Now.Year.ToString());
int select_yr = 0;
for(int i = (current_yr-3); i <= current_yr; i++)
{
select_yr = current_yr - (i - (current_yr-3));
yearList.Add(new SelectListItem() { Value = select_yr.ToString(), Text = select_yr.ToString() });
}
return yearList;
}
private IEnumerable<SelectListItem> GetMonthList()
{
List<SelectListItem> monthList = new List<SelectListItem>();
monthList.Add(new SelectListItem() { Value = "JAN", Text = "Jan" });
monthList.Add(new SelectListItem() { Value = "FEB", Text = "Feb" });
monthList.Add(new SelectListItem() { Value = "MAR", Text = "Mar" });
monthList.Add(new SelectListItem() { Value = "APR", Text = "Apr" });
monthList.Add(new SelectListItem() { Value = "MAY", Text = "May" });
monthList.Add(new SelectListItem() { Value = "JUN", Text = "Jun" });
monthList.Add(new SelectListItem() { Value = "JUL", Text = "Jul" });
monthList.Add(new SelectListItem() { Value = "AUG", Text = "Aug" });
monthList.Add(new SelectListItem() { Value = "SEP", Text = "Sep" });
monthList.Add(new SelectListItem() { Value = "OCT", Text = "Oct" });
monthList.Add(new SelectListItem() { Value = "NOV", Text = "Nov" });
monthList.Add(new SelectListItem() { Value = "DEC", Text = "Dec" });
return monthList;
}
So I created a sample project with the data you provided and came up with this :
Controller
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
this.ViewBag.RecordNum = 1;
this.ViewBag.MonthList = this.GetMonthList();
this.ViewBag.YearList = this.GetYearList();
return PartialView();
}
private IEnumerable<SelectListItem> GetYearList()
{
List<SelectListItem> yearList = new List<SelectListItem>();
int current_yr = Convert.ToInt32(DateTime.Now.Year.ToString());
int select_yr = 0;
for (int i = (current_yr - 3); i <= current_yr; i++)
{
select_yr = current_yr - (i - (current_yr - 3));
yearList.Add(new SelectListItem() { Value = select_yr.ToString(), Text = select_yr.ToString() });
}
return yearList;
}
private IEnumerable<SelectListItem> GetMonthList()
{
List<SelectListItem> monthList = new List<SelectListItem>();
monthList.Add(new SelectListItem() { Value = "JAN", Text = "Jan" });
monthList.Add(new SelectListItem() { Value = "FEB", Text = "Feb" });
monthList.Add(new SelectListItem() { Value = "MAR", Text = "Mar" });
monthList.Add(new SelectListItem() { Value = "APR", Text = "Apr" });
monthList.Add(new SelectListItem() { Value = "MAY", Text = "May" });
monthList.Add(new SelectListItem() { Value = "JUN", Text = "Jun" });
monthList.Add(new SelectListItem() { Value = "JUL", Text = "Jul" });
monthList.Add(new SelectListItem() { Value = "AUG", Text = "Aug" });
monthList.Add(new SelectListItem() { Value = "SEP", Text = "Sep" });
monthList.Add(new SelectListItem() { Value = "OCT", Text = "Oct" });
monthList.Add(new SelectListItem() { Value = "NOV", Text = "Nov" });
monthList.Add(new SelectListItem() { Value = "DEC", Text = "Dec" });
return monthList;
}
}
}
View
#{
//string month = "TempEmployments[" + idx + "].EmploymentStartMonth";
//string year = "TempEmployments[" + idx + "].EmploymentStartYear";
}
#Html.DropDownList("some name", (IEnumerable<SelectListItem>)this.ViewBag.MonthList,"some label", new { #class = "field panel-field EmploymentDate", #id = "id" })
<!-- ##Html.ValidationMessageFor(model => model.EmploymentStart) No idea what your model is-->
#Html.DropDownList("some name2", (IEnumerable<SelectListItem>)this.ViewBag.YearList, "some label", new { #class = "field panel-field EmploymentDate", #id = "id2" })
And both dropdowns in my test worked 100% fine. This makes me believe that one either id, name, or label are not being populated correctly. The code you provided does not show how their values are created
Populate your second dropdown just like mine (with a dummy id, label, and name, and see if it renders. Then by process of elimination add them back in.
Also, just a general tip, I would be abstracting those classes out of your controller and into their own classes. Helps keep things a lot cleaner. As well as pass in viewmodels with all of your properties needed. This avoids "Magic strings" and allows code to be easier to update and debug.
As example instead of :
public ActionResult Index()
{
this.ViewBag.RecordNum = 1;
this.ViewBag.MonthList = this.GetMonthList();
this.ViewBag.YearList = this.GetYearList();
return PartialView();
}
I would do
public ActionResult Index()
{
var viewModel = new indexViewModel{
RecordNum = 1,
MonthList = _someService.GetMonthList(),
YearList = _someService.GetYearList()
}
return PartialView(viewModel);
}
then in your view you don't have to worry about magic strings. you can simply do
#Model.MonthList
if I had to guess it has to do with a viewbag being used for a partial view after the page load. Viewbag has its uses but it isn't recommended for drop downs. I would recommend that you build a view model for your partial
public Class EmploymentHistory{
public EmploymentHistory(){
StateList = new List<SelectListItem>();
MonthList = new List<SelectListItem>();
YearList = new List<SelectListItem>();
}
public string RecordNum { get; set; }
public List<SelectListItem> StateList { get; set; }
public string SelectedState { get; set; }
public List<SelectListItem> MonthList { get; set; }
public string SelectedMonth { get; set; }
public List<SelectListItem> YearList { get; set; }
public string SelectedYear { get; set; }
}
then on your controller instead of setting the view bag set the model
EmploymentHistory eh = new EmploymentHistory();
eh.StateList = GetStateList();
etc...
and you can set the defaults for the dropdowns on the controller
eh.SelectedState = //Default value;
return PartialView("_EmploymentHistoryPartial", eh);
on the top of your partial
#model EmploymentHistory
and then change your dropdowns to
#Html.DropDownList(SelectedState, model.StateList, new { #class...
or
#Html.DropDownListFor(x => x.SelectedState, model.StateList, new { #class...
I need help to bind drop-down values from models.
Model.cs
public class BloodGroup
{
public BloodGroup()
{
ActionsList = new List<SelectListItem>();
}
[Display(Name="Blood Group")]
public int Group { get; set; }
public IEnumerable<SelectListItem> ActionsList { get; set; }
}
public class ActionType
{
public int GroupId { get; set; }
public string BloodGroup { get; set; }
}
In the Controller:
List<ActionType> actionType = GetCourses();
bGroup.ActionsList = from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int)action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")?true:false
};
return view;
public List<ActionType> GetCourses()
{
return new List<ActionType> {
new ActionType () { GroupId = 1, BloodGroup = "A+"},
new ActionType () { GroupId = 2, BloodGroup = "B+"},
new ActionType () { GroupId = 3, BloodGroup = "O+" },
new ActionType () { GroupId = 4, BloodGroup = "AB+" },
new ActionType () { GroupId = 5, BloodGroup = "A-"},
new ActionType () { GroupId = 6, BloodGroup = "B-"},
new ActionType () { GroupId = 7, BloodGroup = "O-" },
new ActionType () { GroupId = 8, BloodGroup = "AB-" }
};
}
It successfully return to view. But in view when bind dropdown it throws an error.
in view
#model MyMVC.Models.BloodGroup
#Html.DropDownListFor(m => m.Group, new SelectList(Model.ActionsList, "Value", "Text",true), "-- Select --")</li>
It returns error.
Object reference not set to an instance of an object.
Model.ActionsList is set a Null.
I don't know why it shows null, though I inherit the model.
I need help on how to bind the SelectList value to dropdown
You need to pass a instance of BloodGroup class to the view in your action method, like below:
public ActionResult YourAction()
{
List<ActionType> actionType = GetCourses();
var model = new BloodGroup()
{
ActionsList = (from action in actionType
select new SelectListItem
{
Text = action.BloodGroup,
Value = ((int) action.GroupId).ToString(),
Selected = action.BloodGroup.Equals("A+")
})
};
return View(model);
}
Then in your view:
#model BloodGroup
#Html.DropDownListFor(m => m.Group, Model.ActionsList,"-- Select --")
Notice
Using above example it'll show you the view without errors, but the selected item in your downdownList will NOT show correctly. For showing the selected item correctly, you need to change the type of Grop property to String, like below:
public class BloodGroup
{
//
[Display(Name = "Blood Group")]
public string Group { get; set; }
//
}
Then use above same action method, make your view like:
#model BloodGroup
#Html.DropDownList("Group", Model.ActionsList, "-- Select --")