Friday, December 25, 2009 11:51 PM
Kazi Manzur Rashid
More on Fluent MetadataProvider for ASP.NET MVC
In my last post, one of the thing you complained about maintaining view model and its meta data in two separate place and I admit this becomes a pain when you browse through the codes. I have changed the implementation, so now you will be able to configure the meta data very much like the way you do in Fluent NHibernate or Entity Framework 4.0 Code only version (thanks to Mohamed Meligy from brining it up). There has been also two additional features that I have added, built-in support to show DropDownList/Select element and implicitly adding Email/Url regular expression validation when you apply those in string property.
The following shows both the DataAnnotations and the Fluent version:
DataAnnotations:
public class ProductEditModel
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[Required(ErrorMessage = "Name cannot be blank.")]
[StringLength(64, ErrorMessage = "Name cannot be more than 64 characters.")]
public string Name { get; set; }
[DisplayName("Category")]
[Required(ErrorMessage = "Category must be selected.")]
public Category Category { get; set; }
[DisplayName("Supplier")]
[Required(ErrorMessage = "Supplier must be selected.")]
public Supplier Supplier { get; set; }
[Required(ErrorMessage = "Price cannot be blank.")]
[Range(10, 1000, ErrorMessage = "Price must be between 10.00-1000.00.")]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
}
Fluent:
public class ProductEditModel
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
public Supplier Supplier { get; set; }
public decimal Price { get; set; }
}
public class ProductEditModelConfiguration : ModelMetadataConfigurationBase<ProductEditModel>
{
public ProductEditModelConfiguration()
{
Configure(model => model.Id).Hide();
Configure(model => model.Name).Required("Name cannot be blank.").MaximumLength(64, "Name cannot be more than 64 characters.");
Configure(model => model.Category).DisplayName("Category").Required("Category must be selected.").DropDownList("categories", "[Select category]");
Configure(model => model.Supplier).DisplayName("Supplier").Required("Supplier must be selected.").DropDownList("suppliers", "[Select supplier]");
Configure(model => model.Price).AsCurrency().Required("Price cannot be blank.").Range(10, 1000, "Price must be between 10.00-1000.00.");
}
}
Nothing special, all you have to do is create a class that inherits from ModelMetadataConfigurationBase and pass your view model class as generic definition, then configure the properties. And you no longer have to register it with the BootstrapperTaskBase like you did before, the System.Web.Mvc.Extensibility is intelligent enough to auto register those.
What do you think, again comments and suggestion are greatly appreciated.
Download: github
Filed under: Asp.net, MVC, ASPNETMVC, ASP.NET MVC, Open Source