.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

DropDownListFor causing strange validation error

Posted By:      Posted Date: April 14, 2011    Points: 0   Category :ASP.Net

After trawling the threads I've almost got my DownDownListFor working, but I'm getting a strange validation fail. Please help.

I'm using a .NET 2.5 and an SQL DB back end, made available via the EntityFramework. Validation is setup via MetadataTypes.

The object I'm trying to create is called Deal, it has 3 look-up value fields, LocationId, CompanyId and CategoryId. Each look up field is controlled by a db table/framework entity. On the front end I want the user to select the look up values via a dropdown list.

Each dropdownlist is set up in the same way so I'll concentrate on Category.

Controller GET code:


var cat = db.Categories.ToList().OrderBy(c => c.CategoryName); ;
ViewData["Categories"] = cat;


View Code


<%= Html.DropDownListFor(c => c.Category.CategoryId, new SelectList((IEnumerable)ViewData["Categories"], "CategoryId", "CategoryName"), "-- Select Category --")%>
<%= Html.ValidationMessageFor(model => model.Category.CategoryId)%>


Controller POST code:

if (ModelState.IsValid)

View Complete Post

More Related Resource Links

Validation.Error giving strange behavior

I'm seeing some weird behavior with the Validation.Error attached event. I have a textbox bound to an object that implements the IDataErrorInfo interface. The textbox subscribes to the Validation.Error event. What is weird is that when you put the text box into an invalid state, the Validation.Error event gets triggered twice. Under .NET 3.5, the first time ValidationErrorEventArgs.Action == Removed. The second time ValidationErrorEventArgs.Action == Added. Under .NET 4, it's reversed. The first time ValidationErrorEventArgs.Action == Added. The second time ValidationErrorEventArgs.Action == Removed. Why would it be called twice and why would it work differently under .NET 3.5 and .NET 4? I'm trying to implement a validation summary control similar to the one from ASP.NET. There is a solution here: http://codeblitz.wordpress.com/2009/05/12/wpf-validation-summary-control/ but it doesn't work under .NET 4 because in order for it work work, when you put a control into an invalid state, the last call to the Validation.Error event has to be with ValidationErrorEventArgs.Action == Added. Here is my code:   <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplicatio

Localize framework message from xml validation error


I need to validate an XML through XSD. I am using XMLReader (with XmlReaderSettings and 

Validation_EventHandler to do it). Depend on users preference, I would like to change the output message generated by  Validation_EventHandler in french or english.

Any idea on how to perform this?





BDC Column validation error in DIP



I have created a content type which has a BDC column along with other columns.

This content type is used in a document library. When the user adds a new document of this content type the system is asking for the extra data required for this content type and I am using AJAX to store data in the BDC Column fields.

The adding process goes fine and I am able to check in the document

Now if I check out the document and open it to edit it, a message is shown on the top of the document saying ' Required Properties - To save to the server, correct the invalid or missing required properties' along with 'Edit Properties' button.

When I click on 'Edit Properties' DIP is opening up and the invalid column is not highlighted. After some trial and error I found out that the problem is with the BDC column. When the cut the data from BDC column and paste it again and click on 'Check Item' the error disappears and allows me to check in the document.


Did anyone face any problem like this before. If so please help me out

Also I am new to BDC so please bear with me if I am missing something obvious.



Rejected by custom validation error & ItemAdding



I believe this topic was discussed before in this forum, but I couldn't find it using the exact error I receive: "operation for file.doc was rejected by custom validation on the server"

When I try to add a new word document to my doc library, Word displays this error instead of my custom error message. I set properties.Cancel=true in ItemAdding of my EventHandler, because my validation fails. 

Is there any way to display user properties.ErrorMessage instead of this generic error message?


SharePoint Calendar Error: The "ListViewWebPart" Web Part appears to be causing a problem. Index was

In one specific SharePoint calendar, on one specific week in that calendar when we select the "more items" link in the monthly view (or the expand all option) we get the following error:
The "ListViewWebPart" Web Part appears to be causing a problem. Index was outside the bounds of the array.

Web Parts Maintenance Page: If you have permission, you can use this page to temporarily close Web Parts or remove personal settings. For more information, contact your site administrator.
Troubleshoot issues with Windows SharePoint Services.

If we select a different week the expand and collapse works fine in that calendar.

Very strange error reported in View (Might be a bug in VS2k8?)



As I say in the title of my post this "may" be a bug in VS2k8 Pro, I have seen these strange little things happen before but whenever you utter the word "bug" people tend to get defensive, so I say it "may" be ;)

Basically I have two List(Of MyOwnClass) and I am going to enumerate through these lists on my view.

I add the Import statement to the top of my view so that my custom class can be used on it.

I add a very simple loop,

                    <%For Each CPDCourse As Download In CType(ViewData("CPDAvailable"), List(Of Download))%>
                        <td style="width:100%">
                            <a href="<%=CPDCourse.URL%>">
                            <a href="<%=CPDCourse.URL%>">
                                <img style="border:none;" alt="View Image" src="../../Content/Images/digitaltraining/view.jpg" />

causing 500 server error :(


So, I'm just learning ASP.NET with C#, but this code just makes the page display a "500 - server error page"

the webpage is here: hereswhereyourewrong.net/aspnettest.aspx

the code is as follows:

<%@ Page Language="C#" AutoEventWireup="true" %>
<!-- This program throws up an Error 500: Server Error -->
<!-- I'm not sure why, it compiles just fine. -->
<!-- The last time it was because I had asp:TextBox fields not in a form -->
<!-- but here I just don't know -->
    <head runat="server" >
        <title>ASP.NET With C# Test</title>
        <script runat="server">
            protected void Page_Load(object sender, EventArgs e)
                timeText.Text = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");

            public void updateTime(object sender, EventArgs e)
                timeText.Text = DateTime.Now.ToString("MM-dd-yyyy HH:mm:ss");
        <div style="text-align: center;">
            <form runat="server" ID="timerForm">
                <asp:ScriptManager ID=

strange web service error



I wrote a small little vb.net app that should connect to a MS search server 2010 web service.


I added the web reference, which worked fine, but whenever I run the code, I get this strange error:




I Googled it, but found very little info on it.

Can anyone make sense of it?



How to disable textbox causing validation?

Hello I was running into a strange problem: If I left a textbox blank (in some instances) the textbox would not give up the focus (I could not even close the form).  I learnt later that this was because the text in the textbox was causing validation to fail.  I would have to type in some value (Satisfy validation) before i could close the form. This is problematic for me and I don't want the textbox to behave this way (I do not awnt front end validation).  I desire to have validation done ONLY on the back end.     I thought that I could solve this problem by changing the 'CausesValidation' property in the textbox to false.  This worked!  However it introduced a new problem.  The binding no longer worked on the Textbox.  That is, whatever value I typed in the textbox would not make it to the data set. What is the correct way in solving this problem???  I want validation to be shut off however I still (obviously) need to keep binding in tact...      

Binding of complex entity turns into validation error

consider classic example: Product and Category editing Product in dropdown Id of Category is selected - Category mapped as object with all fields empty except Id when submitting Product edit form - validation gives an error: "Category name is required" (I have Required attribute on Category Name property) How deal with such errors if I want to use built-in validation (if (!ModelState.IsValid))? Writing custom data binder which would fill all such id-only-objects with values from database comes to mind.upd: I did small research of mvc code and found out that validation happens before binding - so this solution would't work. Do you have any other solutions for this problem?

sslstream client certificate validation error

Hi,I have taken server and client program from MSDN2 for sslstream. in that code client certifiacte authetication is made false  i want to enable that and do the code i have done some modification to the code but is giving error "RemoteCertificateNotAvailable" and i think that its not getting the client certificate at server side.So please can any one help me to do client server program using sslstream in which client certificate also needs to be validated.I am attaching my modified code of MSDN2Server sideusing System;using System.Collections;using System.Net;using System.Net.Sockets;using System.Net.Security;using System.Security.Authentication;using System.Text;using System.Security.Cryptography.X509Certificates;using System.IO;namespace Examples.System.Net{    public sealed class SslTcpServer     {        static X509Certificate serverCertificate = null;        // The certificate parameter specifies the name of the file         // containing the machine certificate.        // The following method is invoked by the RemoteCertificateValidationDelegate.        public static bool ValidateClientCertificate(              object sender,              X509Certificate certificate,              X509Chain chain,              SslPolicyErrors sslPolicyErrors)        {            SslPolicyErrors errors = sslPolicyErrors;            if (errors != SslPolicyErrors.None)            {

Validation Error

I have a strange validation error that I sure can't figure out. I'd ignore it, but I'm ending up with a ">" char as the first char rendered in the page. Anybody see anything wrong with this markup? The validation error seems to be on the very first "<table>" tag (in bold). Thanks!<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DashboardII._Default" %><%@ Register Assembly="System.Web.DataVisualization, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %><asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"></asp:Content><asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"><div> <table> <tr> <td style="width:80%"> <asp:Chart ID="Chart1" runat="server" Height="296px" Width="700px" ImageLocation="~/TempImages/ChartPic_#SEQ(300,3)" Palette="BrightPastel" imagetype=&qu

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

Getting the exact page causing an error using Server.GetLastError

Using vb.net/asp.net 2005.in the global.asax page in the application error page I am getting the exception information as follows: Dim CurrentException As Exception = Server.GetLastError() Dim ErrorDetails As String = CurrentException.Message.ToString & "<br><br>" & CurrentException.ToString() To find out when there are any exceptions when users are using the system, then the ErrorDetails are being auto-emailed to members on the IT team to help in troubleshooting.The problem is this:  I want to find out what page is the user is on when the exception happens, sometimes the stacktrace does not list the aspx page.  Does anyone know how to get this information?thanksMC

An error has occurred while trying to access the license validation key file. Please reinstall SQL S

I'm getting this error following installing SQL 2008 on a Windows 2008 R2 OS when trying to open SQL studio, can anyone offer explanation why this is occurring ?  I have installed SQL 2008 SP1. I see many others have also had this issue but cannot find a documented solution and/or confirm reason as to why it occurs.

Strange: Parser Error: Could not load type '_Default'.

i donot have any intentions till now of uploading my web project and just started working on MS VS9.0I made a simple Linq based project (CODE BEHIND used)AS i compiled it i got Parser Error: Could not load type '_Default'.I figured out 2 solutions for this(WHICH I CUDNT FIND IN MANY FORUMS). But nt sure...why doing them solves the problem.SOL 1)The easy way out is to uncheck "place the code in the seperate file" while adding an item.and then adding the statement <%@ Import Namespace="System.Linq" %> on top of ur aspx as in:<%@ Page Language="C#" %><%@ Import Namespace="System.Linq" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">---FURTHER CODE----Sol2)If  we deal whith the CODE behind technique....and have already used "USING System.Linq; in the definition,I found a funny solution to the problem.In ur default page...the top line is<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="<namespace>.<class>" %>Now if i change the keyword from CodeBehind to CodeFile as in:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="<namespace>.<class>

Strange Problem - SSIS Fails with "Syntax error, permission violation, or other nonspecific error".

Hello, I have a strange issue while I am deploying a package to one of the environment server. I have 2 XML Source, in the DataFlow, and one will extracted based on a value of variable that is passed from run time (package is executed from a Job) and other will be extracted all time. The next Step I have is a Execute SQL Task in ControlFlow wihich will execute after DataFlow. This has 2 input parameters and some SQL query that uses the param. Now this one fail on the target environment with below error: failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. I got the error when I did a SSIS Text File Log. Note: If I run the package in BIDS with the same XML files it work. Also when I deploy the package to my Dev Server it works. When I compare the Dev DB with the target environment DB - Both are same. The Service Acount has permission - as I can see the DataFlow task completed. Another Point: The XML Load Data Flow that executes based on the Variable Value does not execute on target environment, even if the value is passed as "True" (It is Boolean Type) But this variable is NOT an input for the Execute SQL task that fails. I am not sure w
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