Style dropdownlist i MVC [duplicate] - c#

This question already has answers here:
#Html.DropDownListFor; How to set different background color for each item in DDL?
(2 answers)
Closed 8 years ago.
How do i go about to style each selectlistitem in my dropdownlist?
Can I give each item an id and access the in css?
Im trying to change the background-color of each item...
Here is the code:
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2))

Html.DropDownListFor renders a , so I don't know why you're saying you're not using tags.
CSS does not care about server-side code, only rendered HTML, so if you're having issues then always show us the rendered HTML and your CSS.
Anyway, to style your element (and remember that because is a "replaced element" in CSS the opportunities for styling are limited, but you can do some cool things: http://bavotasan.com/2011/style-select-box-using-only-css/
You can override the id="" attribute of the so you can use the element selector in CSS, like so:
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2), new { id = "mySelect" })
#mySelect { width: 135px; }
//or
#Html.DropDownListFor(model => model.BehanlingsColour, new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"},
},
"value",
"text",
2), new { class = "dropdown" })
However if you're using this DropDownListFor in a partial view then the id="" attribute won't be unique in the document, which is illegal. Try using different selectors that make use of the context, such as the descendant selector.

You shoud be able to use css pseudo-selectors, such as:
option:nth-child(1) {
background: red;
}

Related

How to make MVC dropdownlist change editor field value

I have an edit view that implements a normal editor text field. The user can manually enter a value that can be saved to the model. However, alongside this editor field I also need a dropdownlist that the user can select from that will edit the editor field. However, the value I am putting in the editor field is not the same as the value selected from the dropdownlist, this value comes from another list which uses the index of the item selected by the dropdownlist to put the value. To illustrate:
I have a text field "Name Id" and and two lists "Name" and "Id". The user will select a "Name" and the view will place the "Id" into the "Name Id" Field.
Example:
Name Id: 2 <----- 2 was entered because Bob was selected
Name:
Alex
Bob
Carl
Dennis
Note: Don't forget to include JQuery reference for js code.
Razor Code:
#{
var domainsList = new SelectList(new []
{
new SelectListItem { Text = "Please Select", Value = "0", Selected = true },
new SelectListItem { Text = "Alex", Value = "1" },
new SelectListItem { Text = "Bob", Value = "2"},
new SelectListItem { Text = "Carl", Value = "3"},
new SelectListItem { Text = "Dennis", Value = "4"}
}, "Value", "Text");
}
#Html.Editor("NameId", new {#class="form-control"})
#Html.DropDownList("Nameslst", domainsList,new {#class="form-control"})
Js Code
<script>
$(function(){
$('#Nameslst').on('change',function(){
$('#NameId').val($(this).val())
})
})
</script>

DropDownListFor initial value not selected

I don't understand why the initial value is not selected when the form is loaded.
Here's my code
model.LUIsUsed = new List<SelectListItem>()
{
new SelectListItem { Value = "0", Text = "Ignore" },
new SelectListItem { Value = "1", Text = "Required" },
new SelectListItem { Value = "2", Text = "Optional" },
};
In my view
#Html.DropDownListFor(x => x.Foo[i].IsUsed, Model.LUIsUsed, new { #class= "form-control input-sm is-used" })
x.Foo[i].IsUsed value is "1", but required is not selected. I can't figure out why.
Is it because x.Foo is an array?
EDIT: When I don't use an array, it works
It looks like there's a problem with DropDownListFor inside a for loop.
I had to build a SelectList and specify the selected value.
#Html.DropDownListFor(x => x.Criterias[i].IsUsed, new SelectList(Model.LUIsUsed,"Value","Text", Model.Criterias[i].IsUsed))
It works, but I would like to know why.

Adding SelectListItem manually to SelectList to use in DropDownListFor

When I create a SelecList I wish to be able to add SelecListItem's manually and to do this I use this code:
List<SelectListItem> Provinces = new List<SelectListItem>();
Provinces.Add(new SelectListItem() { Text = "Northern Cape", Value = "NC" });
Provinces.Add(new SelectListItem() { Text = "Free State", Value = "FS" });
Provinces.Add(new SelectListItem() { Text = "Western Cape", Value = "WC" });
SelectList lstProvinces = new SelectList(Provinces);
Instead of this :
var lstProvinces = new SelectList(new[] { "Northern Cape", "Free State", "Western Cape" });
After I created the SelectList, I pass it to the DropDownListFor via the ViewBag :
Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces)
However when I create the SelectList using the first method, it doesn't work - It adds the 3 values to the dropdown list, but all the values display as:
*screenshot of output
However when I use the second method, it works fine.
I wish to use the first method because i want to be able to specify the Text AND value of each item.
The problem is that SelectList(IEnumerable) constructor doesn't accept SelectListItem's (at least not as SelectListItem to add to its Items collection). It simply accepts collection of some arbitrary objects that will be used to generate completely unrelated internal SelectListItems collection.
If you want, you can use SelectList(IEnumerable, string, string) constructor in such way:
List<SelectListItem> Provinces = new List<SelectListItem>();
Provinces.Add(new SelectListItem() { Text = "Northern Cape", Value = "NC" });
Provinces.Add(new SelectListItem() { Text = "Free State", Value = "FS" });
Provinces.Add(new SelectListItem() { Text = "Western Cape", Value = "WC" });
this.ViewBag.Provinces = new SelectList(Provinces, "Value", "Text");
It will work. But it is unnecessary, because you create complex SelectListItem items that won't be used by the SelectList - it will just treat them as any other data object.
In the same way you can just use some other simpler class in place of SelectListItem:
public class SelectListModel
{
public String Text { get; set; }
public String Value { get; set; }
}
...
Provinces.Add(new SelectListModel() { Text = "Northern Cape", Value = "NC" });
Use DropDownList and name it the same as the model's property name. Mine is "ItemType"
#Html.LabelFor(model => model.ItemType, new { #class = "control-label" })
#Html.DropDownList("ItemType", (IEnumerable<SelectListItem>)ViewBag.ItemTypes, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemType, null, new { #class = "text-danger" })
var types = new List<SelectListItem>();
types.Add(new SelectListItem() { Text = "Select...", Value = string.Empty });
types.Add(new SelectListItem() { Text = "OTC", Value = "0" });
types.Add(new SelectListItem() { Text = "Generic", Value = "1" });
types.Add(new SelectListItem() { Text = "Brand", Value = "2" });
types.Add(new SelectListItem() { Text = "Non-Merchandise", Value = "9" });
ViewBag.ItemTypes = types;
[Required(ErrorMessage = "Item Type is required")]
public Int32 ItemType { get; set; }
you can change your code from
SelectList lstProvinces = new SelectList(Provinces);
to
SelectList lstProvinces = new SelectList(Provinces, "Value", "Text");
and it will display provinces correctly.
You do not need using SelectList.
Instead, put List<SelectListItem> Provinces into ViewBag and return ViewBag.
Then on the View put:
#Html.DropDownList("Dropwonlist", (IEnumerable<SelectListItem>)ViewBag.YourData)
Considering the number of views on this topic, I thought it might help others in giving some further examples of which the option you chose depends on the desired contents of the select list.
I usually prefer to keep the assignment of select dropdown options in a seperate class which is more manageble when creating longer lists, it's also handy to use the same class of optons for more common applications across the app.
C# Class
public class CustomFormsSelectDropdownParams
{
public static IEnumerable<SelectListItem> Example1ItemWidth { get; private set; }
public static IEnumerable<SelectListItem> Example2ItemWidth { get; private set; }
public static List<SelectListItem> Example3ItemWidth { get; private set; }
static CustomFormsSelectDropdownParams()
{
// ---------
// Exmaple 1
// ---------
// This is OK if you only have a
// relatively small amount of options to write.
Example1ItemWidth = new SelectListItem[]
{
// First item different to the remaining range.
new SelectListItem ("100%", "100%"),
new SelectListItem ("5em", "5em"),
new SelectListItem ("6em", "6em"),
new SelectListItem ("7em", "7em"),
new SelectListItem ("8em", "8em"),
new SelectListItem ("9em", "9em"),
new SelectListItem ("10em", "10em")
};
// ---------
// Exmaple 2
// ---------
// This is more practical if you have a large amount of options.
// NOTE: using this example doesnt allow us to insert any options
// that are different from the rest, so limited use cases may apply.
Example2ItemWidth = Enumerable.Range(1, 200).Select(x => new SelectListItem
{
Value = x.ToString() + "em",
Text = x.ToString() + "em",
});
// ---------
// Exmaple 3
// ---------
// This is more practical if you have a large amount of options.
// This example also allows us to add an option that is a different
// to the remaining options in the loop.
// Our first item is bespoke so created seperately.
var firstDefaultItem = new SelectListItem("100%", "100%");
// Provides a range between 10 --> 200em
var remainingItems = Enumerable.Range(10, 191).Select(x => new SelectListItem
{
Value = x.ToString() + "em",
Text = x.ToString() + "em",
});
Example3ItemWidth = new List<SelectListItem>();
// Add out first bespoke item.
Example3ItemWidth!.Add(firstDefaultItem);
// Add the remaining items in a loop.
foreach (var item in remainingItems)
{
Example3ItemWidth.Add(new SelectListItem(item.Text, item.Value));
}
}
}
Sample HTML Code:
<div class="container-fluid">
<div class="row">
<div class="mb-3 col-3" >
<label class="form-label">Example 1</label>
<select class="form-select" asp-items="Classes.CustomForms.CustomFormsSelectDropdownParams.Example1ItemWidth"></select>
</div>
</div>
<div class="row">
<div class="mb-3 col-3" >
<label class="form-label">Example 2</label>
<select class="form-select" asp-items="Classes.CustomForms.CustomFormsSelectDropdownParams.Example2ItemWidth"></select>
</div>
</div>
<div class="row">
<div class="mb-3 col-3" >
<label class="form-label">Example 3</label>
<select class="form-select" asp-items="Classes.CustomForms.CustomFormsSelectDropdownParams.Example3ItemWidth"></select>
</div>
</div>
</div>
All three select dropdowns on the page:
Example 1:
Example 2:
Example 3:
Example 3 was the one that had niggled me for a while, I wasnt sure how to create an select options list as well as adding some other bespoke options at the same time. If i need to to add some more additional besoke options then I would simply add them in what ever order I need, either before the loop, after or in between multiple loops.

Turning bit type into a dropdownlistfor

I have a BIT type in a sql database that I want to turn into a DropDownList.
I pass a model to the page which has an active field. This field is either true or false. I'm adding the ability to modify this column in the database.
Is it possible to create a DropDownListFor that will give them the option of "Active" "Disable" and then return the correct value to the database?
#Html.DropDownListFor(m => m.active, ??)
#Model.active
I have never tried this but how about this:
#Html.DropDownListFor(m=> m.active, new List<SelectListItem>() { new SelectListItem { Text = "Active", Value = "true", Selected = Model.active }, new SelectListItem { Text = "Inactive", Value = "false", Selected = Model.active } })
This solution works great. The only thing I had to change for my code is the "Selected" value if the model value is "False"
#Html.DropDownListFor(m=> m.active, new List<SelectListItem>() { new SelectListItem { Text = "Active", Value = "true", Selected = Model.active }, new SelectListItem { Text = "Inactive", Value = "false", Selected = !Model.active } })
It was displaying Active even though it should display Inactive.

DropdownList Not Showing Selected Item

I am creating a page to edit non-conformance reports. The page takes in a model which is as follows:
On the page, I am trying to show a dropdown list with the current value of the FaultCode property pre-selected. However, it is not working. Instead I have stripped it back to the basics and tried to hard code a pre-selected value, as follows:
#{
var faultCodeList = new List<SelectListItem>
{
new SelectListItem { Text = "Internal Damage", Value = "Internal Damage" },
new SelectListItem { Text = "Customer Problem", Value = "Customer Problem" },
new SelectListItem { Text = "Incorrect Material Supplied", Value = "Incorrect Material Supplied" },
new SelectListItem { Text = "Received Material Damaged", Value = "Received Material Damaged" },
new SelectListItem { Text = "No Test Certificate Supplied", Value = "No Test Certificate Supplied" },
new SelectListItem { Text = "Other", Value = "Other", Selected = true}
};
}
#Html.DropDownList("FaultCode", faultCodeList)
This still does not work. However, if I change the name of the field to something other than FaultCode - i.e FaultCode2 - it works fine!
Why am I seeing this strange behaviour? On the same page I have dropdown lists for other fields, and they are working perfectly...
#Html.DropdownList("FaultCode", new SelectList(faultCodeList, "Value", "Text","Other"))
You need to bind to SelectList than List, so that last parameter you can mention the selected value is "Other".

Categories