I am using MVC 2 and following the example here: Using Data Annotation Validators with the Entity Framework
When I click the Create button in my Create View nothing happens. The ModelState.IsValid is true always. What could be wrong?
Product.cs
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MyProject.Mvc.Models
{
[MetadataType(typeof(ProductMetaData))]
public partial class Product
{
}
public class ProductMetaData
{
[Required(ErrorMessage = "Description is required")]
public object Description { get; set; }
}
}
ProductController.cs
public ActionResult Create()
{
Product portal = new Product() { };
return View(new ProductFormViewModel(portal));
}
[HttpPost]
public ActionResult Create([Bind(Exclude = "ProductId")]FormCollection collection)
{
if (ModelState.IsValid)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
}
}
// If we got this far, something failed, redisplay form
return View();
}
Create.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MyProject.Mvc.Models.ProductFormViewModel>" %>
<%= Html.ValidationSummary("Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.ProductId) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.ProductId) %>
<%= Html.ValidationMessageFor(model => model.Product.ProductId) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.ProductName) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.ProductName) %>
<%= Html.ValidationMessageFor(model => model.Product.ProductName) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Product.Description) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Product.Description) %>
<%= Html.ValidationMessageFor(model => model.Product.Description) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
ProductFormViewModel.cs
using System.Web.Mvc;
namespace MyProject.Mvc.Models
{
public class ProductFormViewModel
{
public Product Product { get; private set; }
public ProductFormViewModel(Product product)
{
Product = product;
}
}
}