MVC/C#: DropDownListFor not selecting 'selected' item - c#

ok, I have a situation where I need to have multiple DDLs of 'BayTypes' that use the same dictionary, which isn't a problem. One DDL for each of 'n' BayOptions. I'm passing a dictionary to my view as 'BayTypes' like this:
(Controller)
var bayTypes = _bayTypeRepository.GetBayTypes().ToList();
property.BayTypes = bayTypes.ToDictionary(g => g.Name, g => g.BayTypeGuid.ToString());
(View)
var overrideValue = item.BayTypeOverride ? item.BayTypeOverrideValue.BayTypeGuid.ToString() : string.Empty;
var result = (from x in Model.BayTypes
select new SelectListItem()
{
Text = x.Key,
Value = x.Value,
Selected = x.Value == overrideValue <-- ***this is working***
});
if (item.BayTypeOverride == true)
{
#Html.DropDownListFor(x => x.BayTypes, result, new { #Name = "BayOptionsToSubmit[" + aCounter + "].BayTypeOverrideValue" })
}
else
{
#Html.DropDownListFor(x => x.BayTypes, result, new { #Name = "BayOptionsToSubmit[" + aCounter + "].BayTypeOverrideValue", #style = "display:none;" })
}
The correct item IS getting selected in the 'result' object. If I step through, and watch 'result', I can see that 'Selected = true' for the right one... but it's not selecting in the DDLFor when it renders...
What am I missing?

Ultimately, what determines the "selected" item in a drop down is ModelState, not the SelectListItem.Selected property. ModelState is composed from the following sources: Request, ViewData, ViewBag, and finally Model.
Check the values of Request["BayTypes"], ViewData["BayTypes"], ViewBag.BayTypes, and Model.BayTypes. If any of those has a different value from what you're expecting to be selected, that's your problem, particularly if the value is not even in the ballpark.
For example, a common cause of this is developers storing their actual select list choices in something like ViewBag.Foo and then trying to apply that to a dropdown bound to Model.Foo. The select list itself at that point becomes the selected item in ModelState, rather than the one particular value you selected.

Solved it... Changed to a .DropDownList (no 'For') and passed in the 'name' as the 'result' var created earlier. Works.
var overrideValue = item.BayTypeOverride ? item.BayTypeOverrideValue.BayTypeGuid.ToString() : string.Empty;
var result = (from x in Model.BayTypes
select new SelectListItem()
{
Text = x.Key,
Value = x.Value,
Selected = x.Value == overrideValue
});
if (item.BayTypeOverride)
{
#Html.DropDownList("result", result, htmlAttributes: new { #Name = "BayOptionsToSubmit[" + aCounter + "].BayTypeOverrideValue" })
}
else
{
#Html.DropDownList("result", result, htmlAttributes: new { #Name = "BayOptionsToSubmit[" + aCounter + "].BayTypeOverrideValue", #style = "display:none;" })
}

Related

Default selected value in mvc5 dropdown

I have a linq query that is binded to a #Html.dropdownfor. If I assign a value to the user's account and leave the page. When I go back to the page, It's default value or preselected value is "Choose a schedule" even when I have a value assigned to it from before. I need it to preselect to the value already stored in the database. It was preselecting correctly with this
ScheduleBuilderList = _context.ScheduleBuilder.ToList()
until I binded LINQ query.
How can I get the database value to the be default value selected in dropdown without messing up the LINQ?
#Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum, new SelectList(Model.ScheduleBuilderList, "ScheduleSummary", "ScheduleSummary"), "Choose a schedule", new {#class = "form-control", id="dropdown"})
LINQ
ScheduleBuilderList = _context.ScheduleBuilder.Where(s => s.IsScheduleAssigned == false).ToList()
Full Actionresult code with recommended change below
public ActionResult EmployeeDetails(string id, ScheduleBuilder scheduleBuilder, ApplicationUser applicationUser)
{
var user = _context.Users.SingleOrDefault(e => e.Id == id);
if (user == null)
{
return HttpNotFound();
}
var viewModel = new TierViewModel()
{
ApplicationUser = user,
TierLevel = _context.Tier.ToList(),
ScheduleBuilderList = _context.ScheduleBuilder
.Where(s => s.IsScheduleAssigned == false)
.Select(item => new SelectListItem
{
Text = item.ScheduleSummary,
Value = item.ScheduleSummary,
Selected = item.ScheduleSummary == user.ScheduleSum
})
};
var user1 = _context.Users.ToList();
var schedule1 = _context.ScheduleBuilder.ToList();
return View("EmployeeDetails", viewModel);
}
You could try something like this:
var ScheduleBuilderList = _context.ScheduleBuilder
.Where(s => s.IsScheduleAssigned == false)
.Select(item => new SelectListItem
{
Text = item.ScheduleSummary,
Value = item.ScheduleSummary,
Selected = item.ScheduleSummary == "usersvalue"
});
Where the literal "usersvalue" should be replaced the value of ApplicationUser.ScheduleSum for which you are interested in. Then you should change a bit also your View, like below:
#Html.DropDownListFor(m => m.ApplicationUser.ScheduleSum,
Model.ScheduleBuilderList,
"Choose a schedule",
new {#class = "form-control", id="dropdown"})
and your Model should replace the type of ScheduleBuilderList with the following type:
IEnumerable<SelectListItem>

Concatenate two fields in select list (C#)

I use a viewbag to create a select list and I want to Show two fields concatenated together. However, it is crashing on my view. Here is the viewbag code:
ViewBag.PackageId = new SelectList(db.Packages.Where(p => p.status == "A"), "u_package_id", "u_package_id" + "'-'" + "package_nme");
This should work
ViewBag.PackageId = db.Packages.Where(p => p.status == "A")
.Select(p => new SelectListItem
{
Text = p.u_package_id + "-" + p.package_nme,
Value = p.u_package_id
};
The 2nd and 3rd parameters of the SelectList constructor are strings that must match the names of properties in your model (in your case your don't have a property named "u_package_id-package_nme" hence the error).
In the controller, generate a collection of SelectListItem
ViewBag.PackageList = db.Packages.Where(p => p.status == "A").Select(p => new SelectListItem()
{
Value = p.u_package_id, // may need .ToString() depending on the property type
Text = string.Format("{0}-{1}", p.u_package_id, p.package_nme)
}
Side note: Suggest you name your properties to reflect what they are (i.e. its a collection of items, not an ID so PackageList, not PackageId) and this would be necessary anyway if the model your binding to contains a property named PackageId
Thanks to deramko, I have my answer. He was 99% of the way there. Here is the final code:
ViewBag.PackageId = db.Packages.Where(p => p.status == "A")
.Select(p => new SelectListItem
{
Text = p.u_package_id + "-" + p.package_nme,
Value = p.u_package_id.ToString()
});

ASP.NET MVC: DropDownListFor doesn't select any option when rendered

I have this to populate a drop down list in an ASP.NET MVC view.
C#
ViewBag.Employees = new SelectList(
_employeeRepository.GetAll(),
"ID",
"LastName",
employeeToClientContract.EmployeeID);
CSHTML
#Html.DropDownListFor(model => model.EmployeeID, ViewBag.Employees as IEnumerable<SelectListItem>, "Please select")
NOTE: For some reason this works
ViewBag.OverridePhysicians = new SelectList(
_employeeRepository.GetAll().Where(e => e.EmployeeTypes.TypeType == 1),
"ID",
"LastName",
employeeToClientContract.OverridePhysicianID);
#Html.DropDownListFor(model => model.OverridePhysicianID, ViewBag.OverridePhysicians as IEnumerable<SelectListItem>, "Please select")
Debugging this I can see that the Selected property is set to true when it should be. But when the view is rendered, none of the options in the list is selected.
Any ideas?
UPDATE: The problem wasn't with any of the control configurations. My problem was extra spaces in my URL. All I had to do was call .Trim() to fix the problem.
$('#itemsTable').bootstrapTable({
}).on('click-row.bs.table', function (e, row, $element) {
window.location.href = "/EmployeeToClientContract/Edit?employeeId=" + row[0].toString().trim() + "&clientContractId=" + row[2].toString().trim();
});
DropDownListFor Helper use model.EmployeeID value to set selected value in DropdownList. This property has value?
Also, why are facing so much difficults with SelectList? Don't you want to populate ViewBag like this:
ViewBag.Employees = _employeeRepository
.GetAll()
.Select(x => new SelectListItem
{
Text = x.LastName,
Value = x.ID.ToString(),
Selected = employeeToClientContract.EmployeeID == x.ID
});

Update the selected dropdownlist value base on value from another linq query

I use the following code to get the LOV for dropdownlist and setting a selected value as well:
ViewData["dropDown_Color"] = correspondingDropDownValue
.Select(j =>
new SelectListItem {
Text = j.ListOfValue,
Value = j.ListOfValue,
Selected = j.ListOfValue
== x.DefaultValue
})
.ToList();
Now that I have a dropdownlist in my ViewData, I want to update the selected value of this ViewData["dropDown_Color"] base on the following query
var userPref = from m in db.UserColorPref
where m.UserID.Equals(userSessionID)
select m;
The value to be updated can be access by userPref.color. May I know how to achieve my objective?
Use this
List<SelectListItem> selectlist = ViewData["dropDown_Color"] as List<SelectListItem>;
selectlist.ForEach(x =>
{
x.Selected = x.Value == userPref.color;
});
You can achieve it as follows:
ViewData["dropDown_Color"] = new SelectList(YourSelectList, "Value", "Text", selectedValue);

MVC3 dropdownlistfor

I would like to make a dropdown list, with the numbers 0-10. So users can rate something.
At the moment, I have a label: #Html.LabelFor(model=> model.RATE)
How can I modify this code that I will have a dropdown box? And that the value of the dropdown box will be stored in model.RATE?
The label is working, but it would be much better to have a dropdown menu.
SOLUTION:
#Html.DropDownListFor(model => model.RATE, Enumerable.Range(0,11).Select( x => new SelectListItem { Text = x.ToString() }));
Just create a list of SelectListItem objects that contain the ratings, and then use Html.DropDownListFor with the rating stored in your model (Model.RATE).
#{
var ratings = new List<SelectListItem>();
for( var i = 0; i <= 10; i++ ) {
days.Add( new SelectListItem { Text = i.ToString(), Value = i.ToString(), Selected = Model.RATE == i } );
}
}
#Html.DropDownListFor( x => x.RATE, ratings )
#Html.DropDownListFor(model => model.RATE, new SelectList(Enumerable.Range(0, 11)))
This will do the data binding to the form and from the form
#Html.DropDownListFor(m => m.RATE, Model.RateSelectList, "<- Select Option ->")
Model.RateSelectList would be of type IEnumerable<SelectListItem>, m.RATE would be your nullable integer(int?) property. The third parameter would be your default text that would show if m.RATE is null.

Categories

Resources