MVC3 dropdownlistfor - c#

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.

Related

DropDownListFor Not Assigning to Selected Value

I'm running into a problem where my DropDownListFor is not defaulting to the selected value that I've created in my new List. What am I doing wrong? I've looked up many of the solutions that was provide, but none seem to fit what I was doing.
Here is my Controller Code:
List<SelectListItem> queryPlanGroupList = new List<SelectListItem>();
queryPlanGroupList = (from t in db.PlanGroups
orderby t.Name ascending
select new SelectListItem()
{
Text = t.Name,
Value = t.ID.ToString(),
Selected = (t.ID == plans.PlanGroup.ID)
}).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;
Here is my View Code:
<div class="form-group">
#Html.LabelFor(model => model.PlanGroup, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.PlanGroup, (List<SelectListItem>)ViewBag.PlanGroupList , "- Select one -", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PlanGroup, "", new { #class = "text-danger" })
</div>
The Html.DropDownListFor method uses the first parameter (the expression which specifies your view model proeprty) value to set the selected option. The helper method also discard any Selected attribute you set on the SelectListItems to the default value (false).
So you should set the PlanGroup property value in your GET action method to the value you want to be pre-selected when the SELECT element is rendered.
var queryPlanGroupList = (from t in db.PlanGroups
orderby t.Name ascending
select new SelectListItem()
{
Text = t.Name,
Value = t.ID.ToString()
}).ToList();
ViewBag.PlanGroupList = queryPlanGroupList;
yourViewModel.PlanGroup = plans.PlanGroup.ID;
return View(yourViewModel);
Assuming PlanGroup property of your view model is of same type as the ID property of PlanGroup class.
Another option is to use the Html.DropDownList helper, which respects the Selected attribute on the SelectListItem
The below should also work with your current action method code.
#Html.DropDownList("PlanGroupList", null, "Select one", new { #class = "form-control" })
I personally prefer to use Html.DropDownListFor over Html.DropDownList as it is more strongly typed IMHO. I also prefer view model properties instead of using ViewBag to pass the list of options :)
I believe it is because you need to set the default value using your model. In your ViewModel, set the PlanGroup to be the value you want to be selected by default.
The Selected field for a SelectList is only used for DropDownList, not DropDownListFor.
Edit: Turns out that is the case. See a similar question here.

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

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;" })
}

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
});

Convert IDictionary<Guid,string> to the IEnumerable<SelectListItem>

How i can convert IDictionary<Guid,string> to the IEnumerable<SelectListItem>?
I want to use string as SelectListItem.
If you want to use the guid as the value, you can use
dictionary.Select(x => new SelectListItem { Text = x.Value, Value = x.Key })
Well you could just use
dictionary.Values().Select(x => new SelectedListItem { Text = x })
Just be aware that it may not be in a useful order: Dictionary<,> is inherently unordered (or rather, the order may change and shouldn't be relied on).
Something like this should do what you want:
var selectList = dictionary
.OrderBy(kvp => kvp.Value) // Order the Select List by the dictionary value
.Select(kvp => new SelectListItem
{
Selected = kvp.Key == model.SelectedGuid, // optional but would allow you to maintain the selection when re-displaying the view
Text = kvp.Value,
Value = kvp.Key
})
.ToList();
Using LINQ, you could do something like,
var theSelectList = from dictItem in dict
select new SelectListItem()
{
Text = dictItem.Value,
Value = dictItem.Key.ToString()
};

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);

Categories

Resources