.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

Why does Model Validation Errors steal my markup?

Posted By:      Posted Date: September 23, 2010    Points: 0   Category :ASP.Net


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

View Complete Post

More Related Resource Links

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


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

Code Name Avalon: Create Real Apps Using New Code and Markup Model


The presentation subsystem in the next version of Windows, code-named "Longhorn," offers powerful new capabilities to developers. This subsystem, code-named "Avalon," allows developers to take advantage of its capabilities through a new markup language code-named "XAML." In addition, modern object-oriented programming languages such as C# and Visual Basic .NET can be used to tie everything together. Because most applications written to Avalon will probably be a mix of XAML and programming code, this article discusses XAML tags used to control page layout along with the procedural code written to respond to events.

Charles Petzold

MSDN Magazine January 2004

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?


Validation errors and getting the site disability accessibile


I'm using the official validator from the World Wide Web Consortium, http://validator.w3.org/

And I'm seeing a lot of validation errors. What can be done to make my sharepoint publishing site a little more accessibility friendly?


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

SQL Server + ASP.NET Security Validation + HTML Markup Security

Hey everyone!I have an application, that for example, the customer gives me their Address. I store it in my database using the below code:        Dim connectionString As String = ConfigurationManager.ConnectionStrings("DMBConnstring").ConnectionString         Dim insertSql As String = "INSERT INTO BasicUserProfile(UserGuid, Firstname, Lastname, Nickname, Address1, City, State, Zip, DOB, Gender, SeekingGender, Sexuality, SeekingSexuality, HaveKids, WantKids, BodyType, SeekingBodyType, Ethnicity, SeekingEthnicity, Religion, SeekingReligion, Smoking, SeekingSmoking, Education, SeekingEducation, Relationship, SeekingRelationship) " _         & "VALUES (@UserGuid, @Firstname, @Lastname, @Nickname, @Address1, @City, @State, @Zip, @DOB, @Gender, @SeekingGender, @Sexuality, @SeekingSexuality, @HaveKids, @WantKids, @BodyType, @SeekingBodyType, @Ethnicity, @SeekingEthnicity, @Religion, @SeekingReligion, @Smoking, @SeekingSmoking, @Education, @SeekingEducation, @Relationship, @SeekingRelationship)"         Dim connectionString As String = ConfigurationManager.ConnectionStrings("myconnstring").ConnectionString        Dim insertSql As String = "INSERT INTO BasicUserProfile(UserGuid, Firstname, Lastname, Nickname, A

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

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

How to make the validation Errors as Compilation Errors



As part of our Custom Activities, we are adding few validation errors to the Metadata.These errors are appearing in design time under Error List; but still we are able to build the project successfully.

Our requirement is that, if there is any validation error, it should throw compilation error.

Looking for some good suggetions to implement this behaviour.



Assistant Consultant

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

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.



Detecting cell validation errors from a DataGrid

Is there a way, from the DataGrid, to work out if any of it's rows have a validation error? I know you can use the Validation.HasError property at the level of an individual cell, but it seems that information doesn't filter back up to the DataGrid so you can test a simple property on the DataGrid to see if there are any errors (i.e. if you get Validation.HasError at the DataGrid level, it's always false regardless of whether or not there are any errors).

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.


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