Search Results

Search found 17503 results on 701 pages for 'bean validation model'.

Page 7/701 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • ASP.NET MVC Html.ValidationSummary(true) does not display model errors

    - by msi
    I have some problem with Html.ValidationSummary. I don't want to display property errors in ValidationSummary. And when I set Html.ValidationSummary(true) it does not display error messages from ModelState. When there is some Exception in controller action on string MembersManager.RegisterMember(member); catch section adds an error to the ModelState: ModelState.AddModelError("error", ex.Message); But ValidationSummary does not display this error message. When I set Html.ValidationSummary(false) all messages are displaying, but I don't want to display property errors. How can I fix this problem? Here is the code I'm using: Model: public class Member { [Required(ErrorMessage = "*")] [DisplayName("Login:")] public string Login { get; set; } [Required(ErrorMessage = "*")] [DataType(DataType.Password)] [DisplayName("Password:")] public string Password { get; set; } [Required(ErrorMessage = "*")] [DataType(DataType.Password)] [DisplayName("Confirm Password:")] public string ConfirmPassword { get; set; } } Controller: [HttpPost] public ActionResult Register(Member member) { try { if (!ModelState.IsValid) return View(); MembersManager.RegisterMember(member); } catch (Exception ex) { ModelState.AddModelError("error", ex.Message); return View(member); } } View: <% using (Html.BeginForm("Register", "Members", FormMethod.Post, new { enctype = "multipart/form-data" })) {%> <p> <%= Html.LabelFor(model => model.Login)%> <%= Html.TextBoxFor(model => model.Login)%> <%= Html.ValidationMessageFor(model => model.Login)%> </p> <p> <%= Html.LabelFor(model => model.Password)%> <%= Html.PasswordFor(model => model.Password)%> <%= Html.ValidationMessageFor(model => model.Password)%> </p> <p> <%= Html.LabelFor(model => model.ConfirmPassword)%> <%= Html.PasswordFor(model => model.ConfirmPassword)%> <%= Html.ValidationMessageFor(model => model.ConfirmPassword)%> </p> <div> <input type="submit" value="Create" /> </div> <%= Html.ValidationSummary(true)%> <% } %>

    Read the article

  • SQL SERVER – Creating All New Database with Full Recovery Model

    - by pinaldave
    Sometimes, complex problems have very simple solutions. Let us see the following email which I received recently. “Hi Pinal, In our system when we create new database, by default, they are all created with the Simple Recovery Model. We have to manually change the recovery model after we create the database. We used the following simple T-SQL code: CREATE DATABASE dbname. We are very frustrated with this situation. We want all our databases to have the Full Recovery Model option by default. We are considering the following methods; please suggest the most efficient one among them. 1) Creating a Policy; when it is violated, the database model can be fixed 2) Triggers at Server Level 3) Automated Job which goes through all the databases and checks their recovery model; if the DBA has not changed the model, then the job will list the Databases and change their recovery model Also, we have a situation where we need a database in the Simple Recovery Model as well – how to white list them? Please suggest the best method.” Indeed, an interesting email! The answer to their question, i.e., which is the best method to fit their needs (white list, default, etc)? It will be NONE of the above. Here is the solution in one line and also the easiest way: Just go to your Model database: Path in SSMS >> Databases > System Databases >> model >> Right Click Properties >> Options >> Recovery Model - Select Full from dropdown. Every newly created database takes its base template from the Model Database. If you create a custom SP in the Model Database, when you create a new database, it will automatically exist in that database. Any database that was already created before making changes in the Model Database will not be affected at all. Creating Policy is also a good method, and I will blog about this in a separate blog post, but looking at current specifications of the reader, I think the Model Database should be modified to have a Full Recovery Option. While writing this blog post, I remembered my another blog post where the model database log file was growing drastically even though there were no transactions SQL SERVER – Log File Growing for Model Database – model Database Log File Grew Too Big. NOTE: Please do not touch the Model Database unnecessary. It is a strict “No.” If you want to create an object that you need in all the databases, then instead of creating it in model database, I suggest that you create a new database called maintenance and create the object there. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: PostADay, Readers Question, SQL, SQL Authority, SQL Query, SQL Server, SQL Tips and Tricks, T SQL, Technology

    Read the article

  • Yahoo sitemap validation

    - by Joel
    Hello, I am trying to submit sitemap.xml (index) to Yahoo Site Explorer but with no luck. I tried using website feed option in the site explorer to submit the sitemap, but I got validation errors. However, when submitting the same sitemap to google webmaster tools, the sitemap was validated successfully. Could it be for the fact that I am using sitemap with image tag: <image:image> <image:loc>http://www.domain.com/pic.jpg</image:loc> <image:title>picture</image:title> </image:image> When I tried validating the sitemap with inline tools such as http://www.xml-sitemaps.com/validate-xml-sitemap.html and http://www.w3.org/2001/03/webdata/xsv the error I received was: Attempt to load a schema document from http://www.google.com/schemas/sitemap-image/1.1 (source: new namespace) for http://www.google.com/schemas/sitemap-image/1.1, failed: Not recognised as W3C XML Schema or RDDL: html However, the declaration of the sitemap I use in the top of the document is the same as suggested by Google on their official page at http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=178636 : <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"> <url> Any ideas how to resolve this issue? Thanks, Joel Thanks, Joel

    Read the article

  • Weblogic 10.3.0 : Loosing a stateless session bean in the bean pool

    - by KlasE
    Hi, We have a strange situation where we loose a Stateless SessionBean in a Bean Pool in Weblogic 10.3.0 Since we only have one bean in the pool, this effectively hangs all incoming calls. We do not want more than one instance in the pool because of application restrictions. In the Weblogic admin console, we can see that there are 1 instance in the bean pool, 0 beans in use and 1 waiting incoming request. The question is, what can have caused the system to not send the request to the one obviously free bean instance? This happens after several hours and over 100000 incoming requests, and the same scenario worked fine in the old weblogic 8 environment. We get the following stacktrace: "[ACTIVE] ExecuteThread: '5' for queue: 'weblogic.kernel.Default (self-tuning)'" waiting for lock java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject@b0d484 TIMED_WAITING sun.misc.Unsafe.park(Native Method) java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:198) java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2054) weblogic.ejb.container.pool.StatelessSessionPool.waitForBean(StatelessSessionPool.java:269) weblogic.ejb.container.pool.StatelessSessionPool.getBean(StatelessSessionPool.java:111) weblogic.ejb.container.manager.StatelessManager.preInvoke(StatelessManager.java:148) weblogic.ejb.container.internal.BaseRemoteObject.preInvoke(BaseRemoteObject.java:227) weblogic.ejb.container.internal.StatelessRemoteObject.preInvoke(StatelessRemoteObject.java:52) com.mycompany.beans.MessageLogFacace_n73y0z_EOImpl.isMyStuffValid(MessageLogFacace_n73y0z_EOImpl.java:261) com.mycompany.beans.MessageLogFacace_n73y0z_EOImpl_WLSkel.invoke(Unknown Source) weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:589) weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230) weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:477) weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363) weblogic.security.service.SecurityManager.runAs(Unknown Source) weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:473) weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118) weblogic.work.ExecuteThread.execute(ExecuteThread.java:201) weblogic.work.ExecuteThread.run(ExecuteThread.java:173) Any help would be very welcome. Regards Klas

    Read the article

  • Setting spring bean property value using ref-bean

    - by Apache Fan
    Hi, I am trying to set a property value using spring. <bean id="velocityPropsBean" class="com.test.CustomProperties" abstract="false" singleton="true" lazy-init="false" autowire="default" dependency-check="default"> <property name="properties"> <props> <prop key="resource.loader">file</prop> <prop key="file.resource.loader.cache">true</prop> <prop key="file.resource.loader.class">org.apache.velocity.runtime.resource.loader.FileResourceLoader</prop> <prop key="file.resource.loader.path">NEED TO INSERT VALUE AT STARTUP</prop> </props> </property> </bean> <bean id="velocityResourcePath" class="java.lang.String" factory-bean="velocityHelper" factory-method="getLoaderPath"/> Now what i need to do is insert the result from getLoaderPath into file.resource.loader.path. The value of getLoaderPath changes so it has to be loaded at server startup. Any thoughts how i can inset the velocityResourcePath value to the property?

    Read the article

  • Anemic Domain Model, Business Logic and DataMapper (PHP)

    - by sunwukung
    I've implemented a rudimentary ORM layer based on DataMapper (I don't want to use a full blown ORM like Propel/Doctrine - for anything beyond simple fetch/save ops I prefer to access the data directly layer using a SQL abstraction layer). Following the DataMapper pattern, I've endeavoured to keep all persistence operations in the Mapper - including the location of related entities. My Entities have access to their Mapper, although I try not to call Mapper logic from the Entity interface (although this would be simple enough). The result is: // get a mapper and produce an entity $ProductMapper = $di->get('product_mapper'); $Product = $ProductMapper->find('[email protected]','email'); //.. mutaute some values.. save $ProductMapper->save($Product) // uses __get to trigger relation acquisition $Manufacturer = $Product->manufacturer; I've read some articles regarding the concept of an Anemic Domain model, i.e. a Model that does not contain any "business logic". When demonstrating the sort of business logic ideally suited to a Domain Model, however, acquiring related data items is a common example. Therefore I wanted to ask this question: Is persistence logic appropriate in Domain Model objects?

    Read the article

  • php form-input validation

    - by fusion
    i have a html page in which i enter data which then submits and inserts in a database on a php page. how would i validate in php that the data received is not a duplicate of the data in the database? any help appreciated.

    Read the article

  • jQuery Validation Plugin: Validating Checkboxes with Different Names

    - by Michael
    I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked. I know there are a few posts on here already trying to answer this question. The solution that seems to be most logical to me is the answer posted on Question 1734840, but I can't seem to get it working! What's wrong with my code? Or any other new coding ideas to get this working? I have set the class on all of them to 'require-one'. My jQuery code is $(document).ready(function(){ $("#itemForm").validate({ highlight: function(element, errorClass, validClass) { $(element).addClass(errorClass).removeClass(validClass); $(element.form).find("label[for=" + element.name + "]") .addClass("radioerror"); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass(errorClass).addClass(validClass); $(element.form).find("label[for=" + element.name + "]") .removeClass("radioerror"); }, rules: { 'require-one': { required : { depends: function(element) { var allBoxes = $('.require-one'); if (allBoxes.filter(':checked').length == 0) { if (allBoxes.eq(element).length != 0) { return true; } } return false; } } } , }, errorPlacement: function(error, element) { if ( element.is("#other_descrip") ) error.appendTo("#othererror" ); if ( element.is("#itemlist") ) error.appendTo("#itemerror" ); } }); });

    Read the article

  • ASP.NET MVC - Custom validation message for value types

    - by Giovanni Galbo
    When I use UpdateModel or TryUpdateModel, the MVC framework is smart enough to know if you are trying to pass in a null into a value type (e.g. the user forgets to fill out the required Birth Day field) . Unfortunately, I don't know how to override the default message, "A value is required." in the summary into something more meaningful ("Please enter in your Birth Day"). There has to be a way of doing this (without writing too much work-around code), but I can't find it. Any help? EDIT Also, I guess this would also be an issue for invalid conversions, e.g. BirthDay = "Hello".

    Read the article

  • email validation javascript

    - by fusion
    is this javascript function (checkValidity) correct? function checkTextBox(textBox) { if (!checkValidity(textBox.getValue())) displayError("Error title", "Error message", textBox); textBox.focus(); } function checkValidity(e) { var email; email = "/^[^@]+@[^@]+.[a-z]{2,}$/i"; if (!e.match(email)){ return false; else return true; } }

    Read the article

  • Zend framework currency validation

    - by Dan
    How can I validate (a form element in this case) to ensure that the value is a currency? Have looked at Zend_Validate_Float. Needs to check that value is between 0 and 2dp. Ideally locale-aware (as ZVF is) to allow for locale specific formatting (thousands, decimal as comma/dot) Would also want to extend to allow/disallow negative values And provide optional upper/lower limits. Is the key, as I can do 3. and 4. with a chain. Do I need regex?

    Read the article

  • validation using jquery

    - by fusion
    i'm trying to validate an html page using jquery, but nothing happens. it's a simple page, yet the textboxes aren't validated. this is the code: <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="~/jquery.js/"></script> <script type="text/javascript" src="~/jquery-validate/jquery.validate.js/"></script> <script type="text/javascript"> $(document).ready(function(){ var validator = $("#submitForm").validate({ debug: true, rules: { author: "required", quote: "required" }, messages: { author: "Name of Author required" quote: "Please enter Quote" }, errorPlacement: function(error, element) { error.appendTo( element.parent().top() ); } ); }); </script> <body> <div class="container"> <div class="center_div"> <h2>Submit Your Quote</h2> <fieldset> <form id="submitForm" action="qinsert.php" method="post"> <div class="error" style="display:none"></div> <div class="field"> <label>Author: </label> <input name="author" type="text" class="required" minLength=3> <span class="error"></span> </div><br /> <div class="field"> <label>Quote: </label> <textarea name="quote" cols=22 class="required" minLength=5></textarea> <span class="error"></span> <br /> </div> <input id="button1" type="submit" value="Submit" class="submit" /><br /> <input id="button2" type="reset" value="Reset" /> </form> </fieldset> </div> </div> what is wrong with the code? thank you!

    Read the article

  • jQuery Validation: Validating Checkboxes with Different Names

    - by Michael
    I have a set of 4 checkboxes, all with different names, and require that at least 1 is checked. I know there are a few posts on here already trying to answer this question. The solution that seems to be most logical to me is the answer posted on Question 1734840, but I can't seem to get it working! What's wrong with my code? Or any other new coding ideas to get this working? I have set the class on all of them to 'require-one'. My jQuery code is $(document).ready(function(){ $("#itemForm").validate({ highlight: function(element, errorClass, validClass) { $(element).addClass(errorClass).removeClass(validClass); $(element.form).find("label[for=" + element.name + "]") .addClass("radioerror"); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass(errorClass).addClass(validClass); $(element.form).find("label[for=" + element.name + "]") .removeClass("radioerror"); }, rules: { 'require-one': { required : { depends: function(element) { var allBoxes = $('.require-one'); if (allBoxes.filter(':checked').length == 0) { if (allBoxes.eq(element).length != 0) { return true; } } return false; } } } , }, errorPlacement: function(error, element) { if ( element.is("#other_descrip") ) error.appendTo("#othererror" ); if ( element.is("#itemlist") ) error.appendTo("#itemerror" ); } }); });

    Read the article

  • rails validation of presence not failing on nil

    - by holden
    I want to make sure an attibute exists, but it seems to still slip thru and I'm not sure how better to check for it. This should work, but doesn't. It's a attr_accessor and not a real attribute if that makes a difference. validates_presence_of :confirmed, :rooms {"commit"=>"Make Booking", "place_id"=>"the-kosmonaut", "authenticity_token"=>"Tkd9bfGqYFfYUv0n/Kqp6psXHjLU7CmX+D4UnCWMiMk=", "utf8"=>"✓", "booking"=>{"place_id"=>"6933", "bookdate"=>"2010-11-22", "rooms"=>[{}], "no_days"=>"2"}} Not sure why my form_for returns a blank hash in an array... <% form_for :booking, :url => place_bookings_path(@place) do |f| %> <%= f.hidden_field :bookdate, { :value => user_cart.getDate } %> <%= f.hidden_field :no_days, { :value => user_cart.getDays } %> <% for room in pricing_table(@place.rooms,@valid_dates) %> <%= select_tag("booking[rooms][][#{room.id}]", available_beds(room)) %> <% end %> <% end %>

    Read the article

  • Validating a single radio button is not working in available javascript validation script Part-2

    - by OM The Eternity
    Hi All I am available with the solution given by @Tomalak for MY QUESTION could you pls help me out with it as its giving me an error in firebug as : frm.creatorusers is undefined [Break On This Error] var rdo = (frm.creatorusers.length ...rm.creatorusers : frm.creatorusers; I used the code for validating radio button as: function valDistribution(frm) { var mycreator = -1; var rdo = (frm.creatorusers.length > 0) ? frm.creatorusers : frm.creatorusers; for (var i=0; i<rdo.length; i++) { if (rdo[i].checked) { mycreator = 1; //return true; } } if(mycreator == -1){ alert("You must select a Creator User!"); return false; } }

    Read the article

  • Using an actor model versus a producer-consumer model?

    - by hewhocutsdown
    I'm doing some early-stage research towards architecting a new software application. Concurrency and multithreading will likely play a significant part, so I've been reading up on the various topics. The producer-consumer model, at least how it is expressed in Java, has some surface similarities but appears to be deeply dissimilar to the actor model in use with languages such as Erlang and Scala. I'm having trouble finding any good comparative data, or specific reasons to use or avoid the one or the other. Is the actor model even possible with Java or C#, or do you have do use one of the languages built for the purpose? Is there a third way?

    Read the article

  • EJB 3 Session Bean Design for Simple CRUD

    - by sdoca
    I am writing an application that's sole purpose in life is to do CRUD operations for maintaining records in database. There are relationships between some of the tables/entities. Most examples I've seen for creating session beans deals with complex business logic/operations that interact with many entities which I don't have. Since my application is so very basic, what would be the best design for the session bean(s)? I was thinking of having one session bean per entity which had CRUD the methods defined. Then I thought of combining all of those session beans into a single session bean. And then I found this blog entry which is intriguing, but I must admit I don't understand all of it (what is a ServiceFacade?). I'm leaning towards session bean/entity class, but would like to hear more experienced opinions. Thanks.

    Read the article

  • RESTful application validation. Mix of frontend/backend validation. How?

    - by Julian Davchev
    Hi. Using RESTful for all backend persistance and operations. I just pass data from frontend (by frontend I don't mean clientside but the part that is making use of the REST) to rest and data gets back success or no with validation errors if any. Thing is I have stuff that should be validated on frontend too..like csrf tokens, captcha etc. Only reasonable way is I mix validation coming from token/captcha checks and validation errors coming back from REST. Issue with this will be kinda automation as I wouldn't want form field names to map 1:1 with backend field names use by the REST documents. Any pointers ideas are more than welcome.

    Read the article

  • Model format for small game

    - by DeadMG
    I'm writing my own small-time game from scratch, and now I'm looking to start creating models. I've been wondering- what is the best model format to use? Given that I will be writing the model loading code myself and using whatever program generates them. Ideally, I'd look for a format that has fairly wide support between modelling programs, so I can pick the one I like most to actually perform the building, and the format itself would be relatively simple to load, rather than having all of the latest features.

    Read the article

  • Backbone.js Model validation fails to prevent Model from saving

    - by Benjen
    I have defined a validate method for a Backbone.js Model. The problem is that even if validation fails (i.e. the Model.validate method returns a value) the post/put request is still sent to the server. This contradicts what is explained in the Backbone.js documentation. I cannot understand what I am doing wrong. The following is the Model definition: /** * Model - Contact */ var Contact = Backbone.Model.extend({ urlRoot: '/contacts.json', idAttribute: '_id', defaults: function() { return { surname: '', given_name: '', org: '', phone: new Array(), email: new Array(), address: new Array({ street: '', district: '', city: '', country: '', postcode: '' }) }; } validate: function(attributes) { if (typeof attributes.validationDisabled === 'undefined') { var errors = new Array(); // Validate surname. if (_.isEmpty(attributes.surname) === true) { errors.push({ type: 'form', attribute: 'surname', message: 'Please enter a surname.' }); } // Validate emails. if (_.isEmpty(attributes.email) === false) { var emailRegex = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,6}$/i; // Stores indexes of email values which fail validation. var emailIndex = new Array(); _.each(attributes.email, function(email, index) { if (emailRegex.test(email.value) === false) { emailIndex.push(index); } }); // Create error message. if (emailIndex.length > 0) { errors.push({ type: 'form', attribute: 'email', index: emailIndex, message: 'Please enter valid email address.' }); } } if (errors.length > 0) { console.log('Form validation failed.'); return errors; } } } }); Here is the View which calls the Model.save() method (see: method saveContact() below). Note that other methods belonging to this View have not been included below for reasons of brevity. /** * View - Edit contact form */ var EditContactFormView = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'createDialog', 'formError', 'render', 'saveContact', 'updateContact'); // Add templates. this._editFormTemplate = _.template($('#edit-contact-form-tpl').html()); this._emailFieldTemplate = _.template($('#email-field-tpl').html()); this._phoneFieldTemplate = _.template($('#phone-field-tpl').html()); // Get URI of current page. this.currentPageUri = this.options.currentPageUri; // Create array to hold references to all subviews. this.subViews = new Array(); // Set options for new or existing contact. this.model = this.options.model; // Bind with Model validation error event. this.model.on('error', this.formError); this.render(); } /** * Deals with form validation errors */ formError: function(model, error) { console.log(error); }, saveContact: function(event) { var self = this; // Prevent submit event trigger from firing. event.preventDefault(); // Trigger form submit event. eventAggregator.trigger('submit:contactEditForm'); // Update model with form values. this.updateContact(); // Enable validation for Model. Done by unsetting validationDisabled // attribute. This setting was formerly applied to prevent validation // on Model.fetch() events. See this.model.validate(). this.model.unset('validationDisabled'); // Save contact to database. this.model.save(this.model.attributes, { success: function(model, response) { if (typeof response.flash !== 'undefined') { Messenger.trigger('new:messages', response.flash); } }, error: function(model, response) { console.log(response); throw error = new Error('Error occured while trying to save contact.'); } }, { wait: true }); }, /** * Extract form values and update Contact. */ updateContact: function() { this.model.set('surname', this.$('#surname-field').val()); this.model.set('given_name', this.$('#given-name-field').val()); this.model.set('org', this.$('#org-field').val()); // Extract address form values. var address = new Array({ street: this.$('input[name="street"]').val(), district: this.$('input[name="district"]').val(), city: this.$('input[name="city"]').val(), country: this.$('input[name="country"]').val(), postcode: this.$('input[name="postcode"]').val() }); this.model.set('address', address); } });

    Read the article

  • and or operator in validates_presence_of of a Ruby on Rails model

    - by user284194
    I have an entry.rb model and I'm trying to make a semi-complicated validation. I want it to require one or more of the following fields: phone, phone2, mobile, fax, email or website. How would you write the intended code? Would something like this work? validates_presence_of :phone and or :phone2 and or :mobile and or :fax and or :email and or :website

    Read the article

  • null values from listbox, are not evaluated in the model binding of ASP.NET-MVC

    - by Jorge
    The model validation doesn't evaluates the attributes linked to listbox values if you don't select at least one of them. This way is not possible to do a model evaluation using DataAnnotations in order to inform required values. The controller: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using TestValidation.Models; namespace TestValidation.Controllers { [HandleError] public class HomeController : Controller { private SelectList list = new SelectList(new List<string>() { "Sao Paulo", "Toronto", "New York", "Vancouver" }); public ActionResult Index() { ViewData["ModelState"] = "NOT EVAL"; ViewData["ItemsList"] = list; return View(); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(MyEntity entity) { if (ModelState.IsValid) { ViewData["ModelState"] = "VALID"; } else { ViewData["ModelState"] = "NOT VALID!!!"; } ViewData["ItemsList"] = list; return View(); } public ActionResult About() { return View(); } } } The View: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestValidation.Models.MyEntity>" %> <asp:Content ID="indexTitle" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server"> <h2> Validation Test</h2> <p> <% using (Html.BeginForm()) {%> <fieldset> <p> ModelState: <%= Html.Encode((string)ViewData["ModelState"])%> </p> <p> <label for="Name"> Name:</label> <%= Html.TextBoxFor(m => m.Name)%> <%= Html.ValidationMessageFor(m => m.Name)%> </p> <p> <label for="ItemFromList"> Items (list):</label> <%= Html.ListBoxFor(m => m.ItemFromList, ViewData["ItemsList"] as SelectList)%> <%= Html.ValidationMessageFor(m => m.ItemFromList)%> </p> <p> <label for="ItemFromCombo"> Items (combo):</label> <%= Html.DropDownListFor(m => m.ItemFromCombo, ViewData["ItemsList"] as SelectList)%> <%= Html.ValidationMessageFor(m => m.ItemFromCombo)%> </p> <p> <input type="submit" value="Submit" /> </p> </fieldset> <% } %> </asp:Content> The Model: using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace TestValidation.Models { public class MyEntity_Validate : ValidationAttribute { public MyEntity_Validate() { this.ErrorMessage = "Validated!. Is <> Toronto"; } public override bool IsValid(object value) { return ((string)value == "Toronto"); } } public class MyEntity { [Required] public string Name { get; set; } [MyEntity_Validate] public string ItemFromList { get; set; } [MyEntity_Validate] public string ItemFromCombo { get; set; } } } Any help would be very much appreciated. Thank you.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >