Mvc c# : Exclude Enum values from DropDownListFor Html helper on .cshtml Page

Author - Webner
30.03.2021
|
0 Comments
||

Suppose we have some enum type in c# as follows :
enum Performance
{
None=-1,
Dissatisfied=0,
Below Average=1,
Average =2,
Good = 3,
Excellent=4,
}

Consider some employee model with a given enum type property.
public class EmployeePerformance{
public int EmpId {get; set;}
public Performance rating{get; set}
…………………………..
………………………..
}

In a model-binded view, we can populate the dropdown items from the enum on the .cshtml page as follows:
@Html.DropDownListFor(model => model.rating, new SelectList(Enum.GetValues(typeof(.Performance)), new {@class = "form-control", onchange ="(this);" }).

Suppose you want to exclude items from the list of items in a dropdown list populated from Enum object,
Following is an example in which enum item with value -1 is removed-
@Html.DropDownListFor(model => model.rating, new SelectList(Enum.GetValues(typeof(.Performance)).Cast().Where(t=>t!=-1).Cast<.Performance>()), new {@class = "form-control", onchange ="(this);" }).

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *