Dropdownlistfor will not show the correct selection
If you want to set the selected value that is coming in Model. You need to do it like this:
@Html.DropDownListFor(m => oProfile.BodyTypeShoulderId,
new SelectList(Model.BodyTypeShoulders,
"Id",
"Name",
oProfile.BodyTypeShoulderId),
new { @class = "form-control input-sm-select" })
The above code will set the dropdown selected value to whatever is in the current Model object BodyTypeShoulderId
The first argument of DropDownListFor
tells that on form post drop down selected value will be mapped with the Model property which is set there (we are passing m => oProfile.BodyTypeShoulderId
) but this not sets selected Value.
For setting selected value you have to pass SelectList
fourth parameter using this overload of SelectList class which is object selectedValue
DropDownListFor Not Selecting Value
After researching for an hour, I found the problem that is causing the selected to not get set to DropDownListFor
. The reason is you are using ViewBag's name the same as the model's property.
Example
public class employee_insignia
{
public int id{get;set;}
public string name{get;set;}
public int insignia{get;set;}//This property will store insignia id
}
// If your ViewBag's name same as your property name
ViewBag.Insignia = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
@Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.Insignia, "Please select value")
The selected option will not set to dropdownlist, BUT When you change ViewBag's name to different name the selected option will show correct.
Example
ViewBag.InsigniaList = new SelectList(db.MtInsignia.AsEnumerable(), "id", "description", 1);
View
@Html.DropDownListFor(model => model.insignia, (SelectList)ViewBag.InsigniaList , "Please select value")
Html.DropdownListFor selected value not being set
Your code has some conceptual issues:
First,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
Some code I would use if I were you to avoid this issues and write better MVC code:
Viewmodel:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
DropDownListFor not respecting Selected property of SelectList
This tends to stump people a lot - apparently the roadmap for MVC 5 includes more intuitive DropDownList helpers.
When you do:
@Html.DropDownListFor(x => x.TimeOption ...)
... the HTML helper will do everything in its power not to use the value you set to Selected = true
in your SelectList
. It will:
- Try to get it from
ModelState
- which it won't get on the GET request - Try to get it from
ViewData
- which it will get, because you have aTimeOption
property on your model.
Only if both of those attempts fail, will it succumb, and use what you asked it to use.
So, in your case, it will use the current value of TimeOption
on your model as the selected value. Which should be fine, because that's what you asked for in your SelectList
anyway ((int)Model.TimeOption
), right?
Wrong. Because it will not cast your property (enum
?) to int
like you do. It will convert it to a string. For an enum
that yields the enumeration's name - e.g. PastMonth
. If TimeOption
is a custom class of yours, it will be the result of ToString()
.
Then, when it doesn't find that string as one of your <select>
values (because they're all integers), it decides not to make anything selected.
In short: SelectListItem.Selected
has no effect on the helper. If your helper call specifies a name (either literally or through a lambda expression), the helper will use anything in ModelState
or ViewData
with that name, and convert it to a string.
In most cases this happens with enumerations. The easiest way to get around it is to use the enumeration's name, rather than its int representation, as the value for the SelectListItem
.
MVC DropDownListFor not selecting value from model
I found the answer! Thanks to all for your help. When I change my code to the following, it works. The code simply specifies the selected value:
@Html.DropDownListFor(
model => Model.adjusterLanguages[i].languageID,
new SelectList(
ViewBag.ForeignLanguages, "Value", "Text",
@Model.adjusterLanguages[i].languageID))
ASP.NET MVC DropDownListFor does not honour SelectListItem.Selected
Try like this:
var selectList = sortedEntries.Select(entry => new SelectListItem
{
Text = entry.Value,
Value = entry.Id
});
return View(new DropDownListModel
{
// The drop down list is bound to ListId so simply set its value
// to some element value in the list and it will get automatically
// preselected
ListId = selectedValue,
SelectList = selectList,
OptionLabel = "Click to Select"
});
and in the view:
<%= Html.DropDownListFor(
m => m.ListId,
new SelectList(Model.SelectList, "Value", "Text"),
Model.OptionLabel,
new { @class = "someClass" }
) %>
There could be one more gotcha: you are trying to change the selected value in a POST action. For example you rendered a form, the user selected some value in the dropdown, submitted the form and in your POST action you do some processing on this selected value and when you redisplay the view you want the drop down list to have some other value selected. In this case you will have to remove the initial selection which is contained in the ModelState or the Html helper will ignore the selected value in the model:
// do this before returning the view and only if your scenario
// corresponds to what I described above
ModelState.Remove("ListId");
DropDownListFor not showing selected value
@Html.DropDownList("FormType", null, "Select", htmlAttributes: new { @class = "form-control" })
Related Topics
How to Stack Divs from Top to Bottom in CSS
Is It Ok to Have Multiple HTML Forms with The Same Name
Is The Copyright Meta Tag Valid in HTML5
How to Center and Crop an Image to Always Appear in Square Shape with CSS
Is It Correct to Use Div Inside Form
Is There a Jdk Class to Do HTML Encoding (But Not Url Encoding)
The Right Way of Setting <A Href=""> When It's a Local File
Overflow-X:Hidden Still Can Scroll
HTML Tab Interface Using Only CSS
CSS Not Loading After Redirect with Htaccess Rewrite Rule
Can't Get The Complete Address While Uploading a File
Can HTML5 Websockets Connect 2 Clients (Browsers) Directly Without Using a Server? (P2P)
CSS 100% Height with Absolute Positioning Top 0 Bottom 0
In The Dom Are Node Ids Case Sensititve
When Multiple Instances of Same Images Are Embedded in an HTML, Does That Load The Image Once