0

I am new to MVC and after searching the whole day, I can't make EnumDropDownListFor working. So I use this topic to ask my first question here at StackOverflow.

I am using .Net 4.6.1 and MVC 5.2.1 with Firefox as browser.

I stripped my project to the bare minimums and could reproduce the error with the following Model, View, Enum and Controller.

MediaTypesController.cs

public ActionResult Create()
{
    return View(new MediaTypeModel());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "mType")] MediaTypeModel mType)
{
    if (ModelState.IsValid)
    {
        return RedirectToAction("Index");
    }
    return View(mType);
}

Create.cshtml

@model Foo.Models.Media.MediaTypeModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>MediaType</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.mType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EnumDropDownListFor(model => model.mType, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.mType, "", 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>

MediaTypeModel.cs

using Foo.DB.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Foo.Models.Media
{
    public class MediaTypeModel
    {
        public MediaTypeList? mType { get; set; }
    }
}

MediaTypeList.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Foo.DB.Enums
{
    public enum MediaTypeList
    {
        General = 0,
        Image = 1,
        Audio = 2,
        Video = 3,
        Office = 4
    }
}

After starting the "Create"- action, I get the correct form in HTML and even the DropDownList is populated correctly. The options has the correct numbers as values. But after hitting the "Create"- button, ModelState.IsValid is false and mType is null.

This behaviour does not change, when I change mType to be not nullable. On the other hand, when I remove mType and add other properties, it works just fine. So I think the process in general is working correctly.

Thanks in advance for your help.

DahinRahn
  • 1
  • 1

0 Answers0