.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

ASP.NET MVC Model Validation

Posted By:      Posted Date: September 06, 2010    Points: 0   Category :ASP.Net
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

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

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

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

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.



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.


How to display model level custom data annotation validation error?


Hello Experts,

I am a MVC newbie & am lost in various ways validation can be implemented in my application.

I created a custom model-level data annotation validator attribute, but am unable to display its error message in the view. Basically, I have let's say 5 properties in the Entity class Job (model-level custom attribute called UniqueKeywords defined on it):

1) LoginID: value comes in the URL

2) Title: Required property level attribute defined on it

3) CatID1, CatID2, CatID3 - 3 categoryIDs - these are dropdowns in the view with same list of keywords in all 3.

I want to mandate that the values picked by the user in all 3 category dropdowns should be different.

With reference to the code pasted below, here is the explanation of what happens:

When I submit the form without specifying a title or picking anything from any of the 3 category dropdowns, the validation occurs for the property level Required attribute as well as model level uniquekeywords attribute, but the error is displayed only next to the required field "Title". I can confirm that the custom validation also works by filling in some text in the Title field & then re-posting the form...this re-displays the view, but the error message "Category cannot be duplicated" is not displayed.

Looks like I am missing s

Model Validation in ASP.NET Web API

Model in MVC is basically a representation of our data structure. So, here in this article, we are going to understand and implement the data annotation technique for applying validation on a model class for an ASP.NET Web API application.

Limitations to Model Validation in Web API

Discussion about limitations to Model validation in ASP.NET Web API using data annotation technique. | Under-Posting and Over-Posting in Model validation.

Binding WPF Controls to an Entity Data Model

In this interview, programming writer, McLean Schofield, demonstrates how to bind WPF controls to an entity data model, using Visual Studio 2010 Beta 1. You can also learn more in the topic: Walkthrough: Binding WPF Controls to an Entity Data Model.

Model View Controller (MVC) for ASP.NET

Model View Controller (MVC) architectures, immediately wonder how the MVC pattern can be applied in an ASP.NET world. This article will demonstrate how the MVC pattern can be applied to an ASP.NET web application and still maintain the basic Microsoft supplied architecture.
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