MVC EnumDropdownListFor bind with enum example

How to bind an Enum to a DropDownList in ASP.NET MVC create a dropdownlistFor from an enum c# - Html.EnumDropdownListFor: Showing a default text ASP.NET MVC Binding DropDownList to Enum Example ASP.NET MVC - Creating a DropDownList helper for enums

In MVC we have EnumDropDownListFor which we can directly bind with our any enum, it is very similar to DropDownListFor. In this article we will try to create an enum and use it into our model and see how we can bind and save it into the database. As we know we cannot keep space in the name of emum members so how we can use a clear text into dropdown than the enum members. It is easy we will use Data Annotation Attribute to achieve the clear text to show. If you will search on net, there are many people will suggest you to create your own helper but it is available in our MVC project and we don't need to write a single line of code, we can directly use it like other TextBoxFor, DropDownListFor...

Let's create a very simple enum called "ProgrammingLanguages", I will use mixed names, means having single word as well as having more than one words, create an enum

public enum ProgrammingLanguages
{
    [Display(Name = "ASP.NET")]
    ASPNet,
    [Display(Name = "C# .NET")]
    CSharp,
    [Display(Name = "Java")]
    Java,
    [Display(Name = "Objective C")]
    ObjectiveC,
    [Display(Name = "Visual Basic .NET")]
    VBNet,
    [Display(Name = "Visual DataFlex")]
    VisualDataFlex,
    [Display(Name = "Visual Fortran")]
    VisualFortran,
    [Display(Name = "Visual FoxPro")]
    VisualFoxPro,
    [Display(Name = "Visual J++")]
    VisualJPlus
}

Note: I used DataAnnotations Display Name, to show the text in dropdown.

Now create a simple StudentModel by using the above enum, I don't want to complicate it so will not use any validation attribute but we can use it as usual. Let's create our model

public class Student
{
    [Key]
    public String StudentId { get; set; }

    [Display(Name="Student Name")]
    public String Student { get; set; }

    [Display(Name = "Languages")]
    public ProgrammingLanguages Language { get; set; }

    [Display(Name = "Student Address")]
    public String Address { get; set; }

    [Display(Name = "City")]
    public String City { get; set; }
}

Point to focus: I used the enum "ProgrammingLanguages" as the data type for our property "Language", that's it for now. Create action methods for get and post the data say "Student" in home controller to test.

[HttpGet]
public ActionResult Student()
{
    var model = new Student();
    return View(model);
}

[HttpPost]
public ActionResult Student(Student model)
{
    var db = new LearningContext();
    db.Students.Add(model);
    db.SaveChanges();

    return View(model);
}

There is nothing in above code, I try to write one httpGet action method and other for httpPost to save the record. In post method simply I amd saving the data into database.

I created the view by using the wizard and and it created the code for me, see only for the EnumDropDownListFor section:

<div class="form-group">
    @Html.LabelFor(model => model.Languages, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EnumDropDownListFor(model => model.Languages, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Languages, "", new { @class = "text-danger" })
    </div>
</div>

It is very similar to the other TextBoxFor code, if it does not clear then let me remove all the label, error, html and CSS Decoration code and it will look like this:

@Html.EnumDropDownListFor(model => model.Languages)

If still you cannot understand then I cannot help you any more :)

Here is the running code and output image:

alt text

Here is the list of overloaded version, which one fit best for you, you can use that.

  1. EnumDropDownListFor(HtmlHelper, Expression>)
  2. EnumDropDownListFor(HtmlHelper, Expression>, IDictionary)
  3. EnumDropDownListFor(HtmlHelper, Expression>, Object)
  4. REnumDropDownListFor(HtmlHelper, Expression>, String)
  5. EnumDropDownListFor(HtmlHelper, Expression>, String, IDictionary)
  6. EnumDropDownListFor(HtmlHelper, Expression>, String, Object)

Here is the complete html code of the page:

@model MyProject.Models.Student
@{
    ViewBag.Title = "Student";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Student</h2>
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Student</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.StudentId, 
                   htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentId, 
                   new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentId, "", 
                   new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.StudentName, 
                   htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.StudentName, 
                    new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.StudentName, "", 
                    new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Languages, 
                 htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EnumDropDownListFor(model => model.Languages, 
                   htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Languages, "", 
                   new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, 
                htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, 
                   new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", 
                   new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.City, 
                htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.City, 
                   new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.City, "", 
                   new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • mvc
  • enumdropdownlistfor
By Ali Adravi On 15 May, 15  Viewed: 27,004

Other blogs you may like

mvc search page example with code

MVC Searh page with pagination: It’s very easy to create a search page in asp.net but when I try to create the same in MVC I faced many problems, how to create model, how to keep searched values in search controls, pagination, I found myself nowhere, so start searching for some good examples but... By Ali Adravi   On 25 Aug 2013  Viewed: 40,241

MVC insert update delete and select records

CRUD (Create, Retrieve, Update and Delete) in MVC. When we start to learn new language, first we try to run an application with “Hello World” and then CRUD functionality. So in this article we will see how to select records from database (with WebGrid, pagination and sort functionality), update a... By Ali Adravi   On 17 Aug 2013  Viewed: 106,061

How to create a single thanks page for entire controller in MVC

Sometimes we need a thanks page say we have user registration, change password, activate account functionality in our application then we need a thanks page after registering with our site, to say thanks for registering with us or showing confirmation that your password is successfully changed or... By Hamden   On 30 Jun 2013  Viewed: 3,771

MVC jquery autocomplete with value and text field

In MVC, autocomplete with jquery is the best way to pull data from database and render according to our requirements, so in this article we will use jquery to show the auto complete text box without any ajax controls. We need a method to get the data from database, a controller method to handle the... By Ali Adravi   On 29 Jun 2013  Viewed: 7,022

Upload files with model data in MVC

Upload multiple files with model data in MVC is really very easy, when I started to test by uploading some files, I though it would be more complicated but it is really not. In my previous post [ASP.Net MVC file upload][1], I promised to post soon about how to upload multiple files. When I was... By Ali Adravi   On 04 Jun 2013  Viewed: 25,571