SelectList with a null selection - c#

I have a bunch of drop down lists in my view, such as this one:
#Html.DropDownListFor(model => model.Process, Model.ProcessList)
They all take in a SelectList based on data from a database table like this:
ProcessList = new SelectList(_db.Processes, "ID", "Name");
where _db.Processes returns a ObjectSet<Process>.
The issue I have is that sometimes the property that is set by the drop down list can be no selection, i.e. null. How can I add a null selection to the SelectList>

#Html.DropDownListFor(model => model.Process, Model.ProcessList,"--Select Process--")
The above line would add --select process-- at the top of select list and if this value is selected, empty string will be posted and bound property will be set to null (Process in this case)

Related

Model Binding is not happening with DropDownList

Here is the link to MVC dotnetfiddle: https://dotnetfiddle.net/k1E6nG
I have a property called as "Result" in my ViewModel which is a List.
Output is an table which can dynamically add rows & each row is an combination of different inputs( like Dropdown & Text Box).
Controller:
rows.Add(new Row() { SQ1 = "2", SQ2 = "Arun", SQ3 = "kumar" });
I am assigning Values to individual Row. In the output, I can see the values getting populated in Text Boxes( Arun & kumar) whereas the DropDown list is not showing the selected value i.e DropDownList in 1st Row should show Benz as selected value
Add an additional parameter to your select list, like this:
<td> #Html.DropDownListFor(model => model.Result[i].SQ1, new SelectList(Model.DDlist,"Value", "Text", Model.Result[i].SQ1)) </td>
Select list takes an optional argument for the selected value, so you can set your selected value there.

How to modify a single entry in SelectList?

In a SelectItem, I get back a collection of objects/values for use in a dropdown list. I need to find a specific item in the returned list and set the Selected property to true if it matches a value (stateCode) that is passed in... I have this which, obviously, doesn't work. The line after the //psuedo comment is where I'd like to make the change. Any idea on how to do this? I don't seem to have access to the properties I want to change...
SelectList retVal = new SelectList(this.db.States.Where(x => x.Col1== someVal), "ValueCol", "TextCol", someVal);
foreach (SelectListItem item in retVal) {
//psuedo
retVal[item.Index].Selected = item.Value == stateCode ? true : false;
}
return retVal;
As requested, here is how I'm rendering the dropdown that this SelectItem is bound to:
<div class="select" id="StateDropDown">
<label for="StateProvince">#Resources.Expert.State_or_Province:</label>
#Html.DropDownListFor(x => x.StateProvince, Model.StateList)
</div>
To assign a selected value to the drop down you don't need to set the value in your select list. all you need to do is set the value on your model when using a for helper. So for your drop down
#Html.DropDownListFor(x => x.StateProvince, Model.StateList)
make sure that you set StateProvince to the value that you want to select. Also make sure that the value of StateProvince Matches a value that is in your SelectList Model.StateList.
It would be appropriate to pass selected value to #Html.DropdownList method.
Assuming stateCode is state you want to be selected.
Like this.
<div class="select" id="StateDropDown">
<label for="StateProvince">#Resources.Expert.State_or_Province:</label>
#Html.DropDownListFor(x => x.StateProvince, Model.StateList, stateCode)

Multiple default selected items in Listbox

I'm looking into creating an Edit page for a Company object that has multiple categories (that are predefined in a list). I have the list being sent through the ViewBag, and have the categories that the user selected in the Create page in an Array thanks to a ViewModel.
I can't figure out a way to have the ListBox prepopulate with the multiple values in my array. I was playing around with jQuery and was able to get one of the values to be selected, but when I try more than one nothing shows up. Any ideas?
#Html.ListBox("Category", new SelectList(ViewBag.Category, "Text", "Value"))
The SelectListItem object has a Selected property to indicate this. So I guess it would come down to how you build the SelectList. Currently you do this:
new SelectList(ViewBag.Category, "Text", "Value")
Which works, but gives you no control over the individual SelectListItems. Instead of building a SelectList, you can build an IEnumerable<SelectListItem> using the same method overload. Initially that might look like this:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value
});
At this point you have more control over the individual items. Now it's just a matter of determining which ones should be selected. How do you determine that? Is it a property on the Category object? Something like this?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.Selected
});
Or perhaps some other condition?:
ViewBag.Category.Select(c => new SelectListItem
{
Text = c.Text,
Value = c.Value,
Selected = c.SomeValue == SomeCondition
});
How you determine that is up to you, and ideally something you can logically add to the backing model being used here.

How can I make dropdownlistfor selected value persist after submit

The following block of code is used to make the selected value of a dropdownlistfor persist after submit:
#Html.DropDownListFor(x => Model.Value, new SelectList(Model.Values, #Model.Value))
In this block of code, Model.Values is a list of strings and the #Model.Value specifies which value is selected.
This block of code works great but I'm trying to do the same thing with a list of SelectListItems (rather than a list of strings). In the following code Model.Values is a list of SelectListItems.
#Html.DropDownListFor(x => Model.Value, Model.Values, Model.Value,
new
{
id = "ValueDD", onchange = "this.form.submit()"
})
Is it possible to use #Model.Value as I did in the first code block to set the selected value?
SelectListItem has a property Selected that needs to be set for the selected item, see http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.ASPX
So in your controler you can just set the Selected property of the item that needs to be selected, assuming you are using the controler to build the list of Model.Values

Using DropDownListFor with model

On my view I am using a list as my model and each list item is of type model, so it looks like this:
#model IEnumerable<UserManager.Models.vw_UserManager_Model>
and I am trying to loop through this list and add a specific property to a DropDownListFor:
#for (int i = 0; i < Model.Count(); i++)
{
Html.DropDownListFor(model => model.ElementAt(i).module, new SelectList(Model, Model.ElementAt(i).module));
}
But when I do this it doesn't render a dropdownmenu on my page.
Can someone help?
You can't render a dropdown list for a model because there is no way of representing the model in its entirety in a dropdown. What is ASP.NET supposed to render?
What you can do if you would like to select a model from a list is to run a LINQ Select query on the list, whereby you create an IEnumerable<SelectListItem> like this:
var selectList = Model
.Select(x => new SelectListItem
{
Name = x.module_name,
Value = x.module
});
I have tried to take the values from the screenshot that you posted. Apologies if I made an error. You get the idea...
What this code does is loop through the collection of your object type (Model.Select) and returns a collection of SelectListItem. If you are unfamiliar with LINQ you need to think of Select as a transformative function. It takes a collection, and for each element transforms it into something else and returns the result. Here, it takes each element of the Model collection and creates a SelectListItem. It then returns an IEnumerable<SelectListItem>.
To render the list on the page you do the following:
#Html.DropDownListFor(Model.MyValue, selectList)
...where Model.MyValue is the variable which receives the selected value (assuming that the value, model is a string, which it appears to be).

Categories

Resources