I'm working in MVC3 with Entity Framework. I've got an entity called Product that has two properties I'd like to validate when a user adds a new record. To do this, I've created a buddy class, as so:
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
}
}
The metadata class is as so:
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
public class ProductMetadata
{
[Required]
public string ProductName { get; set; }
[Range(200, 1000, ErrorMessage = "You must select a valid Account Type")]
public int AccountTypeId { get; set; }
}
}
The view that allows users to add a new record is like this:
@model Rpm.Data.Product
@{
ViewBag.Title = "Product"
}
<script type="text/javascript">
$(document).ready(function() {
//There should be no selection in the drop-down box when the form is first displayed.
document.getElementsByTagName("select")[0].selectedIndex = -1;
}
function formSubmit() {
var form = $("form");
if (form.valid()) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
document.getElementById("frmNewProduct").submit();
return true;
}
else {
return false;
}
}
</script>
<h2>Add New Product</h2>
@using (Html.BeginForm("Create", "Product", new { id = new Product() }, FormMethod.Post, new { id = "frmNewProduct" }))
{
@Html.ValidationSummary(true)
<table>
<tr>
<td>
Product Name
</td>
<td>
@Html.TextBoxFor(m => new Product().ProductName)
@Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td>
Account Type
</td>
<td>
@Html.DropDownListFor(m => new Product().AccountTypeId, new SelectList(Lookup.Instance.AccountTypes, "AccountTypeId", "AccountTypeName"))
@Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td />
<td>
<input type="image" src="@Url.Content("~/Content/images/savebutton.png")" onclick="return formSubmit()" />
</td>
</tr>
</table>
}
(Of course, the above is quite simplified just to avoid overloading the post with code that's not really relevant.)
The problem is that, when the user clicks the Save button, the validation for the ProductName fires just fine and displays the validation message if the field is blank; however, the message for AccountTypeId is never displayed, even if the drop-down is left without a selection (selectedIndex == -1). I know the RangeAttribute on AccountTypeId is being picked up, because when EF tries to save changes to the entities, it throws a DbEntityValidationException, and the text of the ErrorMessage is the custom error message I specified in the metadata. I just can't seem to get it to display on the page and cause the form to fail validation, preventing the user from saving.
Any suggestions as to what I'm doing wrong would be most appreciated!
TIA,
Jeff