2

I have set my enum property as nullable in my model but when I submit my create form I get 'The value 'Select' is not valid for productColor.'

My Model:

  public class product
    {
        public int productId { get; set; }
        public string productName { get; set; }
        public color? productColor { get; set; }
    }

    public enum color
    {
        Red, Green, Blue
    }

My Create View:

            <div class="form-group">
                <label asp-for="productColor" class="control-label"></label>
                <select asp-for="productColor" asp-items="@Html.GetEnumSelectList<color>()" class="form-control">
                 <option>Select</option>
                </select>
                <span asp-validation-for="productColor" class="text-danger"></span>
            </div>

My Controller:

public async Task<IActionResult> Create([Bind("productId,productName,productColor")] product product)
        {
            if (ModelState.IsValid)
            {
                _context.Add(product);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(product);
        }

Result:

The form appears to post null for the productColor value but the model state is invalid at the controller and the view returns with 'The value 'Select' is not valid for productColor.'

2
  • Possible duplicate of SelectList with a null selection Commented Feb 4, 2019 at 11:55
  • 2
    You might consider make a "not applicable" or "None" enum value instead of trying to make no selection Commented Feb 4, 2019 at 11:56

1 Answer 1

9

Update your option element by adding empty value tag

<select asp-for="productColor" asp-items="@Html.GetEnumSelectList<color>()" class="form-control">
        <option value="">Select</option> <!-- notice value="" -->
</select>

If there is not value tag specified browser sends inner text of option as a selected value. So in your case browser sends Select values which is not suitable for controller. This code instructs browser to send empty value which is successfully converted to null in ASP.NET.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.