Selecting the DropDownList Item Through ViewData - asp.net-mvc

I am putting the current pageSize (5,10,15,20,All) in the ViewData inside the Controller. Now, I am trying to set the DropDownlist to set the selected value to the ViewData value.
#Html.DropDownListFor(x => x.GridItems, new SelectList(Model.GridITems, "Value", "Text",ViewData["SelectedItemItemValue"].ToString()))
The above does not work and the first item is automatically selected when the page calls the action.

The first argument to DropDownListFor should be the item in the Model that you want the selected value to be bound to. For example, if you had a property on your model called 'SelectedItemValue' then your code should be as follows
#Html.DropDownListFor(x => x.SelectedItemValue, new SelectList(Model.GridITems, "Value", "Text",ViewData["SelectedItemItemValue"].ToString()))
(the last argument in the select list constructor is for the selected value so this assumes that you have something with a key of SelectedItemItemValue in your ViewData

Related

Mvc DropdownList default selected value by ViewBag

I have filled a viewbag and bound a dropdownlist to it ..like below
var countrylist = ctx.Countries.ToList();
ViewBag.countrylist = new SelectList(countrylist, "ID", "Name",2);
#Html.DropDownList("countrylist", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")
Above I wanted to by default select the second item of countrylist, so I mentioned the value "2" as last parameter of the ViewBag countrylist overload.
But it is not selecting that item by default.
However, If I change the dropdownlist name to something else like below
#Html.DropDownList("countrylist12345", (IEnumerable<SelectListItem>)ViewBag.countrylist, "-Select-")
then it will by default select the 2nd item in countrylist.
Please explain why this is happening ?
Your whole view is most likely strongly typed with some model
#model YourNamespace.SomeModel
This model has a field countrylist which has some value, maybe 0 by default. And because the name of this field is the same as the name of the dropdown itself, the value of this field is what the dropdown uses to determine the default selection. Once you change the name of the dropdown, the connection is gone.
What you can do is make sure that this model you use to strongly type your view is being assigned some value in countrylist field. For example, inside the controller:
SomeModel model = new SomeModel();
model.countrylist = 2;
return View(model);

SelectFor don't set inital value

Using FluentBootstrap and trying to figure out how not to have a default selected item.
#Html.Bootstrap().SelectFor(x => x.Facility, Model.FacilityList)
.SetSize(InputSize.Sm)
.AddAttribute("data-role", "selectize")
I'm assuming I need to use SelectFor and not Dropdown since it's coming from a SelectList.
If Model.FacilityList is a SelectList you set the selected value when you create the SelectList.
Model.FacilityList = new SelectList(options, "Value", "Key", selectedValue);

Why does the DropDownListFor lose the multiple selection after Submit but the ListBoxFor doesn't?

I have read many articles about using MultiSelectList and have yet to understand what is going wrong with my DropDownListFor. I have a ListBoxFor with the same View, ViewModel and data that works fine. I want to use the DropDownListFor because of its optionLabel parameter that ListBoxFor doesn't have.
When the View is first loaded, both the DropDownListFor and the ListBoxFor show the multiple selected items.
When the Submit button is clicked, the selected items collection is posted back to the Controller action okay and the view is refreshed with the ListBoxFor still showing both selected items but the DropDownListFor is only showing one selected item.
The controller action is constructing the MultiSelectList like this:
vm.TasksFilterGroup.Assignees = new MultiSelectList(employees, "Id", "FullName", new string[] { "51b6f06a-e04d-4f98-88ef-cd0cfa8a2757", "51b6f06a-e04d-4f98-88ef-cd0cfa8a2769" });
The View code looks like this:
<div class="form-group">
<label>ListBoxFor</label>
#Html.ListBoxFor(m => m.TasksFilterGroup.SelectedAssignees, Model.TasksFilterGroup.Assignees, new { #class = "form-control", multiple = "multiple" })
</div>
<div class="form-group">
<label>DropDownListFor</label>
#Html.DropDownListFor(m => m.TasksFilterGroup.SelectedAssignees, Model.TasksFilterGroup.Assignees, new { #class = "form-control", multiple = "multiple" })
</div>
Why does the DropDownListFor lose the multiple selection after Submit but the ListBoxFor doesn't?
As the names of the methods imply, DropDownListFor() is for creating a <select> (to select 1 option) and ListBoxFor() is for creating a <select multiple> (to select multiple options). While both methods share a lot of common code, they do produce different results.
Adding the multiple="multiple" attribute changes the display, but it does not change the functionality of the code executed by these methods.
If you inspect the source code, you will note that all the overloads of DropDownListFor() ultimately call the private static MvcHtmlString DropDownListHelper() method, and similarly ListBoxFor() ultimately calls the private static MvcHtmlString ListBoxHelper() method.
Both these methods call the private static MvcHtmlString SelectInternal() method, but the difference is that DropDownListHelper() passes allowMultiple = false while the ListBoxHelper() passes allowMultiple = true.
Within the SelectInternal() method, the key line of code is
object defaultValue = (allowMultiple) ? htmlHelper.GetModelStateValue(fullName, typeof(string[])) : htmlHelper.GetModelStateValue(fullName, typeof(string));
The value of defaultValue is then used when building html for the <option> elements and is used to set the selected attribute(s).
In the case of ListBoxFor(), the value of defaultValue will be the array defined by your SelectedAssignees property. In the case of DropDownListFor() it returns null because the value of your property cannot be cast to string (its an array).
Because defaultValue is null, none of the <option> elements have the selected attribute set and you lose model binding.
As a side note, if you were to set the values of SelectedAssignees in the GET method before you pass the model to the view, you will see that none of them are selected when using DropDownListFor() for the same reasons described above.
Note also that the code for generating the SelectList should just be
vm.TasksFilterGroup.Assignees = new SelectList(employees, "Id", "FullName" });
There is no point setting the 3rd parameter when using either the DropDownListFor() or ListBoxFor() methods because its the value of the property your binding to (SelectedAssignees) that determines which options are selected (the 3rd parameter is ignored by the methods). If you want the options matching those Guid values to be selected, then in the GET method, use
vm.TasksFilterGroup.SelectedAssignees= new string[]{ "51b6f06a-e04d-4f98-88ef-cd0cfa8a2757", "51b6f06a-e04d-4f98-88ef-cd0cfa8a2769" };

Populating a dropdown from ViewData

I have viewdata in my controller which is populated by a list:
List<employee> tempEmpList = new List<employee>();
tempEmpList = context.employees.ToList();
ViewData["tempEmpList"] = tempEmpList;
and I am passing this into my view, the question is, how do I place the content of the viewdata list into a dropdown list?
The display data will be .name from the list item.
I know I could do a foreach on the Viewdata and create a select list, but this seems a bit long winded
You can use the DropDownList html helper:
#Html.DropDownList("SelectedEmployee",
new SelectList((IEnumerable) ViewData["tempEmpList"]), "Id", "Name")
In the SelectList constructor, you can specify which properties of the Employee class should be used as both the text and the value within the dropdown (e.g. "Id", "Name")
The name of the dropdown ("SelectedEmployee") will be used when you post back your data to the server.
Set up your ViewData in the normal way, assigning a Key name that maps to a property in your model that will be bound on Post ...
ViewData["ModelPropertyName"] = new SelectList(...)
Then in your view simply add a Html.DropDownList ...
#Html.DropDownList("ModelPropertyName")
Please try with that. I have tried with MVC5
#Html.DropDownList("SelectedEmployee", new SelectList((System.Collections.IEnumerable) ViewData["tempEmpList"],"id","Name"))

how can get previously selected value in dropdown list in edit page

I am using viewbag to put data in dropdownlist. In my edit page, I want to have selected value as the default value in my dropdown list.
I am sending dropdownlist from the controller class as follows:-
ViewBag.WareHouseId = new SelectList(db.WareHouse, "ID","Description");
my view code for dropdownlist is:-
#Html.DropDownList("WareHouseID","SELECT")
what should I add in the above line to show previously selected value before changing the value of drop downlist.?
Pass the model value to the optionLabel parameter:
#Html.DropDownList("WareHouseID", "SELECT", Model.WareHouseID)

Resources