.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Extreme ASP.NET: Model Validation & Metadata in ASP.NET MVC 2

Posted By:      Posted Date: August 21, 2010    Points: 0   Category :ASP.Net

Scott Allen shows how to improve your user input validation with new features coming out in ASP.NET MVC 2 that easily allow validation on both the client and server.

Scott Allen

MSDN Magazine March 2010

View Complete Post

More Related Resource Links

MetaData Validation needs to live alongside the model it seems


if you use domain service classes you have the option to produce a meta class.  this allows you to add attributes like [Required] etc for simplifying validation.

i have been trying to orgainize my assemblies by splitting out the domain service from the model. 

during that splitting out process i have found that the meta class must reside in the same namespace AND assembly

if they get seperated physically to another project, the code in the meta classes fail to get hit despit being in the same namespace and despite being a partial class.


Multiple forms on the same page MVC2: how to handle (including validation from model)



It should be simple; although I'm having a hard time to figure out the best way to do it. I've MVC2 pages with multiple forms on the same page having different functionalities.

What's the best way to handle this; including the MVC2 way of validation from the model?


XML Signature xsd and Validation Error: Wildcard '##any' allows element causes the content model t

Hello,I'm trying to generate WCF client from Customer's WCF Service which has XML Signature options enabled.When trying to generate client proxy using svcutil I get following errors: Microsoft (R) Service Model Metadata Tool [Microsoft (R) Windows (R) Communication Foundation, Version 3.0.4506.2152] Copyright (c) Microsoft Corporation. All rights reserved. Attempting to download metadata from 'http://donex:51343/WebServices /Service.svc' using WS-Metadata Exchange or DISCO. Error: There was a validation error on a schema generated during export: Source: Line: 1 Column: 13464 Validation Error: Wildcard '##any' allows element 'http://www.w3.org/2000/09/ xmldsig#:HMACOutputLength', and causes the content model to become ambiguous. A content model must be formed such that during validation of an element informati on item sequence, the particle contained directly, indirectly or implicitly ther ein with which to attempt to validate each item in the sequence in turn can be u niquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence. Error: There was a validation error on a schema generated during export: Source: Line: 1 Column: 14410 Validation Error: Wildcard '##any' allows element 'http://www.w3.org/2000/09/ xmldsig#:XPath', and cau

Access Model Validation inside Custom Model Binder.

Hello,Is it possible, inside a Custom Model Binder, to fire "something" that "says" the value is invalid so it gets handled by validation part?Basically, I am getting an exception when the value for the property is invalid.Thank You,Miguel

custom model validation

 Hi all, I am trying to wrap my head around a practical real world scenario where the out-of-the-box model validation framework in MVC2 poses some challenges. Consider the following model classes:     public class Organization    {        public int ID { get; set; }         [Required(ErrorMessage = "Work Address is a required field.")]        [DisplayName("Work Address")]        public Address WorkAddress { get; set; }         [DisplayName("Home Address")]        public Address HomeAddress { get; set; }     }     public class Address    {        [DataType(DataType.Text)]        [DisplayName("Address 1")]        [StringLength(50)]        [Required(ErrorMessage = "Address Line 1 is a required field.")]        public string Address1 { get; set; }         [DataType(DataType.Text)] &n

ASP.NET MVC Model Validation

Hello. I'm trying to validate some input fields.  in this srting - The given key was not present in the dictionary.<%= Html.ValidationMessageFor(model => model[i].FirstName)%>Here some my code:<%@ Page Language="C#" MasterPageFile="~/Views/Shared/MasterPage.Master" Inherits="ModelViewPage<List<MyClass>>"%> ... <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"> </script> <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script> <% Html.EnableClientValidation(); %> <% int count = (int)ViewData["Count"]; %> <% Html.BeginForm(); %> <% for (int i = 0; i < count; i++ ) { %> <%= Html.LabelFor(model => model[i].FirstName)%> <%= Html.TextBoxFor(model => model[i].FirstName)%> <%= Html.ValidationMessageFor(model => model[i].FirstName)%> ...My class: [MetadataType(typeof(MyClass))] public class MyClass { [Required(ErrorMessage = "First Name Requered")] public string FirstName { get; set; } ... Any help in pointing me

Client Object Model - update metadata

Is there a way that I can update the metadata for a document in a document list using a UniqueId without having to speciify the library name? If I know the library name and the ID I know how to update the metadata but what I was hoping was that there would be a way of doing it using a UniqueId without knowing exactly which Library the document is in.

Data Annotation not triggering the client side validation when used on an overriden model property

Hi all, This is a saga from a post that was recently answered:http://forums.asp.net/t/1598187.aspxMy main problem is the lack of client side validation when we use a child model class, the server side validation works like a charm whether you use the virtual/override solution or the new attribute on the child class with the getter and setter linking the property to the base class's one.The client side validation does not work with none of the solutions presented below.This is a sample code of the first solution: [Serializable] public class DateViewModel { ... [Display(typeof(App_GlobalResources.Messages), "Date_Year")] public virtual int? Year { get; set; } ... } [Serializable] public class BirthDateViewModel : DateViewModel { ... [Display(typeof(App_GlobalResources.Messages), "Date_Year")] [YearRange(ErrorMessageResourceType = typeof(App_GlobalResources.Messages), ErrorMessageResourceName = "Validation_Range")] public override int? Year { get; set; } ... } This is a code sample of the second solution : [Serializable] public class DateViewModel { ... [Display(typeof(App_GlobalResources.Messages), "Date_Year")] public int? Year { get; set; } ... } [Serializable] public class BirthDateViewModel : DateViewMod

Why does Model Validation Errors steal my markup?



I have a partial view where I render, if the user has choosen an option, a button that permit the user to generate automatically a value for a certain field. Please give a look at this picture to understand what I mean.

This is achieved using the following markup on the partial view

<%= Html.LabelFor( model => model.IssueCode )%>
<br />
<% if ( Model.HasCodeGenerator ) { %>
    <%= Html.TextBoxFor( model => model.IssueCode, new { style = "width:120px;background-color:#eeeeee;border: solid 2px #dfdfdf", @readonly = "readonly" } )%>
    <% if (Model.ModelState == ModelStateEnum.Add) { %>
        <button id="codeGenerator" style="font-size: 0.7em;margin-right: 10px">Genera codice fascicolo</button>
    <% } %>
<% } else { %>
    <%= Html.TextBoxFor(model => model.IssueCode, new { style="width: 120px" })%>
<% } %>
<%= Html.ValidationMessageFor(model => model.IssueCode, "*")%>

As you can see I append always an Html.ValidationMessageFor() at the end of the input field and a ValidationSummary aut the end of the view.

When the user submits the form the fi

How to assign value to managed metadata field from client object model?


I am working on the project that is based on Client Object Model which should be able to create/update document sets form client side with possibility to fully manage column values. I've managed so far to manipulate from client most of field values but i'm still struggling with managed metadata fields. I know that there isn't any support for this type of field in CSOM so I used TaxonomyClientService which is available from server side and managed to retrieve data necessary for displaying field info. I also discovered that value for this field should be assigned in string form like [WssId]#[TermName]|[TermGUID] to be valid. My problem is how to retrieve WssId. I know it can be found in TaxonomyHiddenList of site collection but since it contains only values that were used in site collection so far it doesn't represent full solution for my problem. Any help would be appreciated.

Thanks in advance..

Validation of model in side model


Hello Everyone,

I have recently started working on ASP.NET with MVC 2 framework, and I am facing following difficulty in validating my data,


In my application the view (ASPX) is divided into tabs (jQuery) and each tab's content is ViewUserControl (ASCX). The main model for the view has collection of sub models for individual tabs. I use RenderPartial method to render view user control.

            <div id="divPage1" class="tabs">
                <% Html.RenderPartial("Tab1", Model.Tabs["Tab1"]); %>

And the user control (Tab1.ascx) refers the specific model for it,

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<NDTMS.Models.Tab1Model>" %>
<table width="100%" align="left" style="caption-side: top" class="details">
            <%= Html.LabelFor(m => m.FirstName) %>
             <%= Html.TextBoxFor(m => m.FirstName) %>

           <%= Html.ValidationMessageFor(m => m.FirstName) %>

            <%= Html.LabelFor(m =&g

User Registration, Model Validation


Hello everyone -

I'm working on my first real MVC application using ADO.NET Entity Data Model and am looking for some advice. I'm starting off with creating a registration page that will accept the following data:

  • Username
  • Email
  • Password
  • Password Confirmation
  • First Name
  • Last Name
  • Job Title
  • Organization

Per my database design, I have two separate models to use here: User and Profile. I'm using MetaData partial classes to add Data Annotations, for obvious reasons. My ViewModel looks like so:

    Public Class RegistrationViewModel
        Public Property User() As User
                Return _user
            End Get
            Set(ByVal value As User)
                _user = value
            End Set
        End Property
        Private _user As User

        Public Property ConfirmPassword() As String
                Return _confirmPassword
            End Get
            Set(ByVal value As String)
                _confirmPassword = value
            End Set
        End Property

        Private _confirmPassword As String

        Public Property Profile() As Profile
                Return _profile
            End Get
            Set(ByVal value As Profile)
                _profile = valu

Metadata buddy class validation issue


I accidentally duplicated the thread and I found no way to delete one of them.

Please, follow the thread here: http://forums.asp.net/t/1614475.aspx




I am using asp.net MVC 2 and Entity Framework 4. I followed the directions to annotate my model classes through a buddy metadata class, so annotations are not lost when EF classes are generated.

It worked fine for a simple class, but now I am working on a more complex class, that requires regular expression and range validation for double type values.

It seems that for this class, MVC is finding the annotation to display the label (I changed the annotation and I saw it changed on my browser), but as far as the validation annotations, it is ignoring it completely.

Any idea before I try something crazy, like downloading the mvc source, and debugging the framework myself?



How can I reuse Model Metadata for custom View Models?



I'm working on an ASP.NET MVC 2 project with some business entities that have metadata dataannotations attributes applied to them (Validation attributes, Display attributes, etc.).

Something like:

//User entity
public class User

[Required(ErrorMessage = "Vorname fehlt")]
[StringLength(MaxNameLength, ErrorMessage = "Vorname ist zu lang")]
public string FirstName { get; set; }

Validation problem with EF model, before annotation validation is evaluated


Hi folks, it's me agian with more EF validation issues...

I am developing a web app in Portuguese, using MVC 2 and EF 4 for the model.

I created a MetadataType class to define the model's validation annotations, where I enter my custom Portuguese messages, like this:


public partial class Property { }

public class PropertyMetaData {

[DisplayName("Status do Projeto:")]

[Required(ErrorMessage = "O status do projeto deve ser selecionado.")]

public object PropertyStatus { get; set; }

[RegularExpression (Regular Expression is blocked by ASP.NET Forum to prevent XSS)]

[Range(0.01, 200000.0, ErrorMessage="A área da propriedade, se fornecida deve ser um número decimal entre 0.01 e 200000")]

[DisplayName("Área Registro (ha):")]

public object Area { get; set; }

Area is a double in my Model. If I enter an invalid number for this field, I receive a standard MVC English error message on the error summary section of my page, and the regular express

Input-validation-Error issue when Model has complex types



I have implemented aps.net mvc validation and it is working fine. Only issue I have "Input-validation-error" css class is not getting applied if model has complex types.

I am using my own data annotations for validation.

Any idea how to resolve  this.



ForeignKey display values based on criteria, metadata model


I have a table with 3 columns, {id,name,display}.  ID being primary key, Name being first string in table(dynamic data will populate any dropdown's with this value, unless overridden), and Display being a bit/boolean. 

I have a custom page(Master/Detail) created making use of asp:DynamicControl and asp:DynamicField.  Several of the associated Controls/Fields are ForeignKeys.  When editing/inserting the controls use the ForeignKey FieldTemplate.  Ideally, this works great!  However, I need a little bit more control over which data items get displayed from the database(selectable values).  This seems like it should be easy, yet, I cannot get my head around it. 

OBJECTIVE: When 'display' == true, show name in list.  When 'display' == false, do not show name in list. 

QUESTION: Is there a way to handle this within the metamodel using metadata attributes, etc...?  Please advise... 



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend