MVC5 Razor html.dropdownlistfor set selected when value is in array
Unfortunately @Html.DropDownListFor()
behaves a little differently than other helpers when rendering controls in a loop. This has been previously reported as an issue on CodePlex (not sure if its a bug or just a limitation)
The are 2 option to solve this to ensure the correct option is selected based on the model property
Option 1 (using an EditorTemplate
)
Create a custom EditorTemplate
for the type in the collection. Create a partial in /Views/Shared/EditorTemplates/AggregationLevelConfiguration.cshtml
(note the name must match the name of the type
@model yourAssembly.AggregationLevelConfiguration
@Html.DropDownListFor(m => m.HelperCodeType, (SelectList)ViewData["CodeTypeItems"])
.... // other properties of AggregationLevelConfiguration
and then in the main view, pass the SelectList
to the EditorTemplate
as additionalViewData
@using (Html.BeginForm())
{
...
@Html.EditorFor(m => m.Configurations , new { CodeTypeItems = Model.CodeTypeItems })
...
Option 2 (generate a new SelectList
in each iteration and set the selectedValue
)
In this option your property CodeTypeItems
should to be IEnumerable<GenericIdNameType>
, not a SelectList
(or just make codeTypes
a public property). Then in the main view
@Html.DropDownListFor(m => m.Configurations[0].HelperCodeType, new SelectList(Model.CodeTypeItems, "Id", "Name", Model.Configurations[0].HelperCodeType)
Side note: there is no need to use new { id = "Configurations[0].HelperCodeType"
- the DropDownListFor()
method already generated that id
attribute
MVC5 - How to set selectedValue in DropDownListFor Html helper
When you use the DropDownListFor()
(or DropDownList()
) method to bind to a model property, its the value of the property that sets the selected option.
Internally, the methods generate their own IEnumerable<SelectListItem>
and set the Selected
property based on the value of the property, and therefore setting the Selected
property in your code is ignored. The only time its respected is when you do not bind to a model property, for example using
@Html.DropDownList("NotAModelProperty", new SelectList(Model.TipoviDepozita, "Id", "Naziv", 2))
Note your can inspect the source code, in particular the SelectInternal()
and GetSelectListWithDefaultValue()
methods to see how it works in detail.
To display the selected option when the view is first rendered, set the value of the property in the GET method before you pass the model to the view
I also recommend your view model contains a property IEnumerable<SelectListItem> TipoviDepozita
and that you generate the SelectList
in the controller
var model = new YourModel()
{
TipoviDepozita = new SelectList(yourCollection, "Id", "Naziv"),
TipPopustaId = 2 // set the selected option
}
return View(model);
so the view becomes
@Html.DropDownListFor(m => m.TipPopustaId, Model.TipoviDepozita, new { @class = "form-control" })
DropDownListFor is not selecting existing value
Try something like below:
@Html.DropDownListFor(model => model.MovieID, new SelectList((IEnumerable)ViewBag.MoviesList, "Value", "Text", Model.MovieID), new { @class = "form-control" })
Where Value is what you want to pass to the action invoked and Text is what you want to show in the dropdown.
Issue with Setting value to dynamic HTML DropDownListFor MVC5
When you are in MYMethod
, do you know which is selected when creating the list? If so you can use the selected
property of the SelectedListItem
and set it to true.
List<SelectListItem> YesNoList = new List<SelectListItem>();
YesNoList.Add( new SelectListItem { Text = "Yes", Value = "1", Selected = true });
YesNoList.Add( new SelectListItem { Text = "No", Value = "0" });
Choose which option is selected on pageload of razor html.dropdownlistfor
You could use shorthand if to determine which option is selected.
@Html.DropDownListFor(m => m.Valeur,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Show", Selected = Model.Valeur == 0 },
new SelectListItem { Value = "1" , Text = "Hide", Selected = Model.Valeur != 0 },
}, new { @class = "myselect" })
How to select default value for DropDownListFor using ASP.NET MVC
If foreach
loop @Html.DropDownListFor(m => m.Role, new SelectList(Model.Role, "RoleId", "RoleName",gt.RoleId), new { @class = "form-control" })
never working correctly, because in razor input/select/textarea
create a unique html name
attribute.But using foreach
it can't do this. so use for
loop or EditorTemplates
rather than foreach
.
Other wise you can generate the html but you can't send list of item in your action.
Example:
@for(var i = 0;i < Model.RoleList.Count;i++)
{
<tr>
<td>@Html.DropDownListFor(m => Model.RoleList[i].RoleId, new SelectList(Model.Role, "RoleId", "RoleName", Model.RoleList[i].RoleId), new { @class = "form-control" })</td>
</tr>
}
Related Topics
Is Is Possible to Export Functions from a C# Dll Like in VS C++
What's the @ in Front of a String in C#
Virtual Member Call in a Constructor
Listing All Permutations of a String/Integer
In C#, Difference Between Public, Private, Protected, and Having No Access Modifier
Protect .Net Code from Reverse Engineering
Difference Between Task and Thread
What Is the Best Workaround For the Wcf Client 'Using' Block Issue
How to Provide User Name and Password When Connecting to a Network Share
How to Post Messages to an Sta Thread Running a Message Pump
Difference Between Property and Field in C# 3.0+
What Are the Correct Version Numbers For C#
The Request Was Aborted: Could Not Create Ssl/Tls Secure Channel
Can't Operator == Be Applied to Generic Types in C#
How to Get Started With Developing Internet Explorer Extensions