I have s simple dropdown which is rendered with:
#Html.DropDownListFor(m => m.Request.Value, new SelectList(items, "Value", "Text", selectedElement), new {})
where Model.Request.Value is of type int and has the value set to -1.
items is build like:
var items = new List<SelectListItem<int>>();
items.Add(new SelectListItem<int>{Text = "10", Value = 10});
items.Add(new SelectListItem<int>{Text = "25", Value = 25});
items.Add(new SelectListItem<int>{Text = "100", Value = 100});
items.Add(new SelectListItem<int>{Text = "All", Value = -1});
The value of selectedElementis 25, which is of type int. However, it always renders the select with All selected, which means value = -1.
Why? And why is there a value selectedElement which get's overridden no matter what?
Your strongly binding to a property in your model, so its the value of the property that determines what is selected. That's how model binding works. If you want "All" to be selected, set the value of Request.Value = -1
The 4th parameter of the SelectList constructor is ignored when binding to a property. The only time it is respected is if you were to use something like #Html.DropDownList("NotAPropertyOfMyModel, new (SelectList(...
Side note: items is IEnumerable<SelectListItem> (which is what the DropDownListFor() method requires) so creating a new IEnumerable<SelectListItem> (which is what SelectList is) is just pointless extra overhead. Your view should be just
#Html.DropDownListFor(m => m.Request.Value, items)
DropDownListFor uses the value of lambda expression to select the item in the dropdown list rather than the last argument of the SelectList constructor.
I believe that the following link includes sample code that should be able to help you:
MVC DropDownList SelectedValue not displaying correctly
Related
The example that I'm looking at is https://www.aspsnippets.com/Articles/Cascading-Dependent-DropDownList-in-ASPNet-MVC.aspx
The example works well. But cannot see how to specify a selected value before passing the model to the view.
You can specify the "Selected" value by
model.Countries.Add(new SelectListItem { Text = country.CountryName, Value = country.CountryId.ToString(), Selected = true });
The Viewmodel results shows the specified item with the Selected = true.
But the dropdown in the view #Html.DropDownListFor(m => m.CountryId, Model.Countries, "Please select", new { onchange = "document.forms[0].submit();" }) just ignores it.
Can anyone see a work around to get the selected value to be displayed?
I'm creating a SelectList to pass to a Html.DropDownList, but the correct value doesn't seem to be populating
var x = new SelectList(new[] {
new SelectListItem() { Value="1", Text="Vanilla"},
new SelectListItem() { Value="2", Text="Chocolate"},
new SelectListItem() { Value="3", Text="Strawberry"}
}, "Value", "Text", "2");
SelectList should take a constructor that takes in the selectedValue:
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
object selectedValue
)
But this only sets the SelectedValue on the entire collection. The individual SelectListItems haven't been set as Selected
Do I need to iterate over them individually and set selected for each as in this question?
The Selected property is being set by the SelectList constructor. The image you have shown is for the items argument (i.e the collection of SelectListItem that you passing to the method), not the result of calling the method.
The constructor does not modify the collection passed to it, it creates a new IEnumerable<SelectListItem>, and if you inspect the value of var x, then you will see that the 2nd SelectListItem (the one with Value = "2") will have its Selected property set to true.
However, the purpose of the SelectListItem class is for use in one of the HtmlHelper methods that generates a <select> (DropDownList(), DropDownListFor(), ListBox() and ListBoxFor() methods) which accept an IEnumerable<SelectListItem> as either the 1st or 2nd argument.
Unless you specifically not binding to a model property (e.g. #Html.DropDownList("NotAModelProperty", Model.YourSelectList)), then setting the Selected property is ignored because the method sets the selected option based on the value of the property your binding to (refer How to set “selectedValue” in DropDownListFor Html helper for more detail), therefore creating a new IEnumerable<SelectListItem> from the first one by using new SelectList(...) is pointless extra overhead.
The reason for using the SelectList constructor is to create an IEnumerable<SelectListItem> from an existing collection of objects, for example
IEnumerable<SelectListItem> options = new SelectList(db.Flavors, "ID", "Name")
which would get the records from the Flavors table, and set the Value based on its ID property, and the Text based on its Name property. It just provides an alternative to using (say)
IEnumerable<SelectListItem> options = db.Flavors.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Name
});
I would like to send the selected dropdown option into model.Feit
Assuming, i need DropDownListFor, then select table, then the dropdown..?
//here's my drop down menu in my controller
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Owner", Value = "0", Selected = true });
items.Add(new SelectListItem { Text = "Leader", Value = "1" });
ViewBag.items = items;
//this works fine, but the selected option has to be inserted into my database when submitted
//the first line shows the label
<div class="editor-label">#Html.LabelFor(model => model.Feit)</div>
//the second line needs to show as a dropdownlist with the 2 options above here
<div class="editor-field">#Html.DropDownListFor(model => model.Feit, "items")</div>
//when the option is selected, and submit is pressed this has to be sent to the db
// this works for all other fields, but my syntax is wrong at , "items"
Since you've already populated an IEnumerable<SelectListItem> in your viewbag, you just need to access it and cast it to ensure the correct DropDownListFor overload is used:
#Html.DropDownListFor(model => model.Feit, (IEnumerable<SelectListItem>)ViewBag.items)
model.Feit should be of type int or something that can hold the value of the selected item.
Use this
#Html.DropDownListFor(m => m.Feit, new SelectList(ViewBag.items, "Id","Name"),"Select")
I am passing in a list of objects to my View via a model
#model MyModel.ObjectViewModel
I am new to MVC and am trying to set the initially selected item of a dropdownlist in my view (modelled after an Edit).
I am then binding this to a drop down list as follows
<label for="ddlObjects">Select Object</label>
#Html.DropDownList("ddlObjects", Model.AllObjectsSelectList, Model.Object.ObjectName)
The above does make the drop down list have the correct object selected initially, but I discovered it is only in the form of text. The real object isn't chosen and as such the value isn't used. How can I have a list of items, say, "Object1" "Object2", etc and have the default be a specific one?
When I'm passing through the item I only know the text value (the name that appears in the drop down list) of the item, I don't know it's inner value so I can't really use SelectListItem {Text = "X", Value= "Y"}
I have searched here and through google, and there are options for setting the intially selected value, however they are using methods like #Html.DropDownList for which doesn't seem to let me specify a control name, and in my controller I specifically reference the name of the control.
My work around wasn't pretty, but it could be easily refactored to be much nicer. It will just be a case of some effort which at present I don't have time for - but I will in the next week or so.
I created a method in my controller which I pass in my list of items (selectList, which you would think would work anyway... but it doesn't) then I work out which is the object I require and set the Selected property to true.
private List<SelectListItem> GetListOfObjectTypes(SelectList selectList, string objectTypeName, string objectTypeId)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (METAObjectType item in selectList.Items)
{
bool isSelected = false;
if (item.Name == objectTypeName)
{
isSelected = true;
}
items.Add(new SelectListItem {Selected= isSelected, Text=item.Name, Value=item.ObjectTypeId.ToString()});
}
return items;
}
I then just pass this through to my View and set it as the list in the #Html.DropDownList and it will now select the correct item by default.
I have something like the following in an ASP.NET MVC application:
IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");
And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery!
I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.
EDIT: This problem has been fixed by ASP.NET MVC RTM.
If you're just trying to to map an IEnumerable<string> to SelectList you can do it inline like this:
new SelectList(MyIEnumerablesStrings.Select(x=>new KeyValuePair<string,string>(x,x)), "Key", "Value");
Try this instead:
IDictionary<string,string> list = GetTheValues();
var selectList = new SelectList(list, "Key", "Value", "SelectedValue");
SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text. Instead it sets the value of each item to "null" or something like that. That's why the selected value has no effect.
Take a look at this: ASP.NET MVC SelectList selectedValue Gotcha
This is as good explanation of what is going on as any.
Try this
ViewBag.Items = list.Select(x => new SelectListItem()
{
Text = x.ToString()
});