Search Results

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

Page 11/701 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • Spring Batch validation

    - by sergionni
    Hello. Does Spring Batch framework provide its specific validation mechanism? I mean, how it's possible to specify validation bean? My validation is result of @NamedQuery - if query returned result, the validation is OK, else - false.

    Read the article

  • Custom Model Binding of IEnumerable Properties in ASP.Net MVC 2

    - by Doug Lampe
    MVC 2 provides a GREAT feature for dealing with enumerable types.  Let's say you have an object with a parent/child relationship and you want to allow users to modify multiple children at the same time.  You can simply use the following syntax for any indexed enumerables (arrays, generic lists, etc.) and then your values will bind to your enumerable model properties. 1: <% using (Html.BeginForm("TestModelParameter", "Home")) 2: { %> 3: < table > 4: < tr >< th >ID</th><th>Name</th><th>Description</th></tr> 5: <% for (int i = 0; i < Model.Items.Count; i++) 6: { %> 7: < tr > 8: < td > 9: <%= i %> 10: </ td > 11: < td > 12: <%= Html.TextBoxFor(m => m.Items[i].Name) %> 13: </ td > 14: < td > 15: <%= Model.Items[i].Description %> 16: </ td > 17: </ tr > 18: <% } %> 19: </ table > 20: < input type ="submit" /> 21: <% } %> Then just update your model either by passing it into your action method as a parameter or explicitly with UpdateModel/TryUpdateModel. 1: public ActionResult TestTryUpdate() 2: { 3: ContainerModel model = new ContainerModel(); 4: TryUpdateModel(model); 5:   6: return View("Test", model); 7: } 8:   9: public ActionResult TestModelParameter(ContainerModel model) 10: { 11: return View("Test", model); 12: } Simple right?  Well, not quite.  The problem is the DefaultModelBinder and how it sets properties.  In this case our model has a property that is a generic list (Items).  The first bad thing the model binder does is create a new instance of the list.  This can be fixed by making the property truly read-only by removing the set accessor.  However this won't help because this behaviour continues.  As the model binder iterates through the items to "set" their values, it creates new instances of them as well.  This means you lose any information not passed via the UI to your controller so in the examplel above the "Description" property would be blank for each item after the form posts. One solution for this is custom model binding.  I have put together a solution which allows you to retain the structure of your modelModel binding is a somewhat advanced concept so you may need to do some additional research to really understand what is going on here, but the code is fairly simple.  First we will create a binder for the parent object which will retain the state of the parent as well as some information on which children have already been bound. 1: public class ContainerModelBinder : DefaultModelBinder 2: { 3: /// <summary> 4: /// Gets an instance of the model to be used to bind child objects. 5: /// </summary> 6: public ContainerModel Model { get; private set; } 7:   8: /// <summary> 9: /// Gets a list which will be used to track which items have been bound. 10: /// </summary> 11: public List<ItemModel> BoundItems { get; private set; } 12:   13: public ContainerModelBinder() 14: { 15: BoundItems = new List<ItemModel>(); 16: } 17:   18: protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 19: { 20: // Set the Model property so child binders can find children. 21: Model = base.CreateModel(controllerContext, bindingContext, modelType) as ContainerModel; 22:   23: return Model; 24: } 25: } Next we will create the child binder and have it point to the parent binder to get instances of the child objects.  Note that this only works if there is only one property of type ItemModel in the parent class since the property to find the item in the parent is hard coded. 1: public class ItemModelBinder : DefaultModelBinder 2: { 3: /// <summary> 4: /// Gets the parent binder so we can find objects in the parent's collection 5: /// </summary> 6: public ContainerModelBinder ParentBinder { get; private set; } 7: 8: public ItemModelBinder(ContainerModelBinder containerModelBinder) 9: { 10: ParentBinder = containerModelBinder; 11: } 12:   13: protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 14: { 15: // Find the item in the parent collection and add it to the bound items list. 16: ItemModel item = ParentBinder.Model.Items.FirstOrDefault(i => !ParentBinder.BoundItems.Contains(i)); 17: ParentBinder.BoundItems.Add(item); 18: 19: return item; 20: } 21: } Finally, we will register these binders in Global.asax.cs so they will be used to bind the classes. 1: protected void Application_Start() 2: { 3: AreaRegistration.RegisterAllAreas(); 4:   5: ContainerModelBinder containerModelBinder = new ContainerModelBinder(); 6: ModelBinders.Binders.Add(typeof(ContainerModel), containerModelBinder); 7: ModelBinders.Binders.Add(typeof(ItemModel), new ItemModelBinder(containerModelBinder)); 8:   9: RegisterRoutes(RouteTable.Routes); 10: } I'm sure some of my fellow geeks will comment that this could be done more efficiently by simply rewriting some of the methods of the default model binder to get the same desired behavior.  I like my method shown here because it extends the binder class instead of modifying it so it minimizes the potential for unforseen problems. In a future post (if I ever get around to it) I will explore creating a generic version of these binders.

    Read the article

  • jquery validation plugin - different treatment for display errors vs. clearing errors

    - by RyOnLife
    I am using the popular jQuery Validation Plugin. It's very flexible with regards to when validations are run (onsubmit, onfocusout, onkeyup, etc.). When validations do run, as appropriate, errors are both displayed and cleared. Without hacking the plugin core, I'd like a way to split the behavior so: Errors are only displayed onsubmit But if the user subsequently enters a valid response, errors are cleared onsubmit, onfocusout, etc. Just trying to create a better user experience: Only yell at them when they submit, yet still get the errors out of their face as soon as possible. When I ran through the options, I didn't see the callbacks necessary to accomplish this. I'd like to make it work without having to hack the plugin core. Anyone have some insights? Thanks.

    Read the article

  • Simple ASP.Net MVC 1.0 Validation

    - by Mike
    On the current project we are working on we haven't upgraded to MVC 2.0 yet so I'm working on implementing some simple validation with the tools available in 1.0. I'm looking for feedback on the way I'm doing this. I have a model that represents a user profile. Inside that model I have a method that will validate all the fields and such. What I want to do is pass a controller to the validation method so that the model can set the model validation property in the controller. The goal is to get the validation from the controller into the model. Here is a quick example public FooController : Controller { public ActionResult Edit(User user) { user.ValidateModel(this); if (ModelState.IsValid) ....... ....... } } And my model validation signature is like public void ValidateModel(Controller currentState) What issues can you see with this? Am I way out to lunch on how I want to do this?

    Read the article

  • Spring validation has error in XML document from ServletContext resource

    - by user1441404
    I applied spring validation in my registration page .but the follwing error are shown in my server log of my app engine server. javax.servlet.UnavailableException: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 22 in XML document from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 22; columnNumber: 30; cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'property'. My code is given below : <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd > <beans:bean name="/register" class="com.my.registration.NewUserRegistration"> <property name="validator"> <bean class="com.my.validation.UserValidator" /> </property> <beans:property name="formView" value="newuser"></beans:property> <beans:property name="successView" value="home"></beans:property> </beans:bean> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".jsp" /> </beans:bean> </beans:beans>

    Read the article

  • Should a model binder populate all of the model?

    - by Richard
    Should a model binder populate all of the model, or only the bits that are being posted? For example, I am adding a product in my system and on the form i want the user to select which sites the new product will appear on. Therefore, in my model I want to populate a collection called "AllAvailableSites" to render the checkboxes for the user to choose from. I also need to populate the model with any chosen sites on a post in case the form does not validate, and I need to represent the form showing the initial selections. It would seem that I should let the model binder set the chosen sites on the model, and (once in the controller method) I set the "AllAvailableSites" on the model. Does that sound right? It seems more efficient to set everything in the model binder but someone is suggesting it is not quite right. I am grateful for any advice; I have to say that all the MVC model binding help online seems to cite really simple examples, nothing complicated. Do I really need a GET and a POST version of a method? Can't they just take the same view model? Then I check in my model binder if it is a GET/POST, and populate all the model accordingly.

    Read the article

  • spring security : Failed to load ApplicationContext with pre-post-annotations="enabled"

    - by thogau
    I am using spring 3.0.1 + spring-security 3.0.2 and I am trying to use features like @PreAuthorize and @PostFilter annotations. When running in units tests using @RunWith(SpringJUnit4ClassRunner.class) or in a main(String[] args) method my application context fails to start if enable pre-post-annotations and use org.springframework.security.acls.AclPermissionEvaluator : <!-- Enable method level security--> <security:global-method-security pre-post-annotations="enabled"> <security:expression-handler ref="expressionHandler"/> </security:global-method-security> <bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"> <property name="permissionEvaluator" ref="aclPermissionEvaluator"/> </bean> <bean id="aclPermissionEvaluator" class="org.springframework.security.acls.AclPermissionEvaluator"> <constructor-arg ref="aclService"/> </bean> <!-- Enable stereotype support --> <context:annotation-config /> <context:component-scan base-package="com.rreps.core" /> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:applicationContext.properties</value> </list> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="initialPoolSize" value="10" /> <property name="minPoolSize" value="5" /> <property name="maxPoolSize" value="25" /> <property name="acquireRetryAttempts" value="10" /> <property name="acquireIncrement" value="5" /> <property name="idleConnectionTestPeriod" value="3600" /> <property name="maxIdleTime" value="10800" /> <property name="maxConnectionAge" value="14400" /> <property name="preferredTestQuery" value="SELECT 1;" /> <property name="testConnectionOnCheckin" value="false" /> </bean> <bean id="auditedSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> <!-- validation is performed by "hand" (see http://opensource.atlassian.com/projects/hibernate/browse/HV-281) <property name="eventListeners"> <map> <entry key="pre-insert" value-ref="beanValidationEventListener" /> <entry key="pre-update" value-ref="beanValidationEventListener" /> </map> </property> --> <property name="entityInterceptor"> <bean class="com.rreps.core.dao.hibernate.interceptor.TrackingInterceptor" /> </property> </bean> <bean id="simpleSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> <!-- property name="eventListeners"> <map> <entry key="pre-insert" value-ref="beanValidationEventListener" /> <entry key="pre-update" value-ref="beanValidationEventListener" /> </map> </property--> </bean> <bean id="sequenceSessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:hibernate.cfg.xml" /> <property name="hibernateProperties"> <value> hibernate.dialect=${hibernate.dialect} hibernate.query.substitutions=true 'Y', false 'N' hibernate.cache.use_second_level_cache=true hibernate.cache.provider_class=net.sf.ehcache.hibernate.SingletonEhCacheProvider hibernate.hbm2ddl.auto=update hibernate.c3p0.acquire_increment=5 hibernate.c3p0.idle_test_period=3600 hibernate.c3p0.timeout=10800 hibernate.c3p0.max_size=25 hibernate.c3p0.min_size=1 hibernate.show_sql=false hibernate.validator.autoregister_listeners=false </value> </property> </bean> <bean id="validationFactory" class="javax.validation.Validation" factory-method="buildDefaultValidatorFactory" /> <!-- bean id="beanValidationEventListener" class="org.hibernate.cfg.beanvalidation.BeanValidationEventListener"> <constructor-arg index="0" ref="validationFactory" /> <constructor-arg index="1"> <props/> </constructor-arg> </bean--> <!-- Enable @Transactional support --> <tx:annotation-driven transaction-manager="transactionManager"/> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="auditedSessionFactory" /> </bean> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider user-service-ref="userDetailsService" /> </security:authentication-manager> <bean id="userDetailsService" class="com.rreps.core.service.impl.UserDetailsServiceImpl" /> <!-- ACL stuff --> <bean id="aclCache" class="org.springframework.security.acls.domain.EhCacheBasedAclCache"> <constructor-arg> <bean class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> </property> <property name="cacheName" value="aclCache"/> </bean> </constructor-arg> </bean> <bean id="lookupStrategy" class="org.springframework.security.acls.jdbc.BasicLookupStrategy"> <constructor-arg ref="dataSource"/> <constructor-arg ref="aclCache"/> <constructor-arg> <bean class="org.springframework.security.acls.domain.AclAuthorizationStrategyImpl"> <constructor-arg> <list> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> <bean class="org.springframework.security.core.authority.GrantedAuthorityImpl"> <constructor-arg value="ROLE_ADMINISTRATEUR"/> </bean> </list> </constructor-arg> </bean> </constructor-arg> <constructor-arg> <bean class="org.springframework.security.acls.domain.ConsoleAuditLogger"/> </constructor-arg> </bean> <bean id="aclService" class="com.rreps.core.service.impl.MysqlJdbcMutableAclService"> <constructor-arg ref="dataSource"/> <constructor-arg ref="lookupStrategy"/> <constructor-arg ref="aclCache"/> </bean> The strange thing is that the context starts normally when deployed in a webapp and @PreAuthorize and @PostFilter annotations are working fine as well... Any idea what is wrong? Here is the end of the stacktrace : ... 55 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [applicationContext-core.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 67 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.config.internalTransactionAdvisor': Cannot resolve reference to bean 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0' while setting bean property 'transactionAttributeSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:328) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:106) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1308) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1067) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:511) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193) at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:86) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:100) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:86) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:404) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ... 73 more Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0': Initialization of bean failed; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:322) ... 91 more Caused by: java.lang.NullPointerException at org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource.getAttributes(DelegatingMethodSecurityMetadataSource.java:52) at org.springframework.security.access.intercept.aopalliance.MethodSecurityMetadataSourceAdvisor$MethodSecurityMetadataSourcePointcut.matches(MethodSecurityMetadataSourceAdvisor.java:129) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:215) at org.springframework.aop.support.AopUtils.canApply(AopUtils.java:252) at org.springframework.aop.support.AopUtils.findAdvisorsThatCanApply(AopUtils.java:284) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findAdvisorsThatCanApply(AbstractAdvisorAutoProxyCreator.java:117) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findEligibleAdvisors(AbstractAdvisorAutoProxyCreator.java:87) at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.getAdvicesAndAdvisorsForBean(AbstractAdvisorAutoProxyCreator.java:68) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:359) at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:322) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:404) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513) ... 97 more

    Read the article

  • MVC2 jQuery Validation & Custom Business Objects

    - by durilai
    I have an application that was built with MVC1 and am in the process of updating to MVC2. I have a custom DLL and BLL, of which the model objects are custom business objects that reside in a separate class library. I was using this validation library in MVC1, which worked great. It worked great, but I want to eliminate the extra plugins and use what is available. Rather than use the Enterprise Library validation attributes I have converted to using DataAnnotations and want to use jQuery validation as the client side validation. My questions are: 1) Is the MicrosoftMvcJQueryValidation JS file still required, where do I download. 2) How to you automate the validation to views that do not have models, IE Membership sign in page? 3) How to you add model errors in a custom business layer. Thanks for any help or guidance.

    Read the article

  • Force validation on bound controls in WPF

    - by Valentin Vasilyev
    Hello. I have a WPF dialog with a couple of textboxes on it. Textboxes are bound to my business object and have WPF validation rules attached. The problem is that user can perfectly click 'OK' button and close the dialog, without actually entering the data into textboxes. Validation rules never fire, since user didn't even attempt entering the information into textboxes. Is it possible to force validation checks and determine if some validation rules are broken? I would be able to do it when user tries to close the dialog and prohibit him from doing it if any validation rules are broken. Thank you.

    Read the article

  • How to combine mvc2 client side validation with other client side validation?

    - by Andrey
    I have a page using mvc2 with client side validation. The client side validation is provided by Microsoft Ajax mvc validation script. This does very well to validate all fields that are related to the model. I also have fields that are never sent to the server such as the confirm password value, and the accept agreement. For these fields i need pure client side validation. I created the javascript to do this, but am now having a hard time integrating the two validatiosn together. I was hoping that i could do something like add another error to an array, or set the page manually to not valid to make sure that the user cannot submit. Basically follow the same approach that i would with normal asp.net validation. I can't find anything like that. In all examples validators are discussed that are connected to parts of the model. What is my best approach here?

    Read the article

  • Excel validation range limits

    - by richardtallent
    When Excel saves a file, it attempts to combine identical Validation settings into a single rule with multiple ranges. This creates one of three issues, depending on the file type you choose to save: When saving as a standard Excel file (Office 2000 BIFF), a maximum of 1024 non-contiguous ranges that can have the same validation setting. When saving as a SpreadsheetML (Office 2002/2003 XML) file, you are limited to the number of non-contiguous ranges that can be represented, comma-delimited in R1C1 format, in 1024 characters. When saving as an Open Office XML (Office 2007 *.xlsx), there is a maximum of 511 non-contiguous ranges that can have the same validation setting. (I don't have Office 2007, I'm using the file converter for Office 2003). Once you bust any of these limits, the remaining ranges with the same Validation settings have their Validation settings wiped. For (1) and (3), Excel warns you that it can't save all of the formatting, but for (2) it does not.

    Read the article

  • ASP.NET validation controls

    - by mehmet6parmak
    Hi All, I want to use Validation Controls but I dont want them to show their Error Messages when invalid data exist. Instead I'm going to iterate through the validation controls and show error messages inside my little ErrorMessage Control for (int i = 0; i < Page.Validators.Count; i++) { if (!Page.Validators[i].IsValid) { divAlert.InnerText = Page.Validators[i].ErrorMessage; return false; } } I'm doing this because i have little space to show the error message. You can ask why are you using validation control if you dont want to show them My asnwer is "I use them for validation logic they handle" I looked the properties of the validation controls and cant find something that wil help me doing this. Any Idea? Thanks

    Read the article

  • NET Framework Validation Library

    - by Kane
    As I see it most applications have a requirement for some form of validation and a number of fantastic free offerings are available (I.E., Fluent Validation, Validation Block, Spring, Castle Windsor, etc). My question is why does the .NET Framework not include any inbuilt validation libraries? I am aware the .NET Framework allows a developer the ability to build their own validation libraries/methods/etc. and anything provided as part of the .NET Framework would not always meet everyone’s needs. But surely something could have been included? ASP.NET has a minimal set of validators but these have not really been extended since .NET 2.0 was released.

    Read the article

  • C# UserControl Validation

    - by Barry
    Hi, I have a UserControl with a Tab Control containing three tabs. Within the tabs are multiple controls - Datetimepickers, textboxes, comboboxes. There is also a Save button which when clicked, calls this.ValidateChildren(ValidationConstraints.Enabled) Now, I click save and a geniune validation error occurs. I correct the error and then click save again - valdiation errors occur on comboboxes on a different tab. If I navigate to this tab and click save, everything works fine. How can this be? I haven't changed any values in the comboboxes so how can the fail validation then pass validation? The comboboxes are bound to a dataset with their selectedValue and Text set. I just don't understand what is happening here. This behaviour also occurs for some textboxes too. The validation rule is that they have to be a decimal - the default value is zero, which is allowed. The same thing happens, they fail validation the first time - I make no changes, click save again and they pass validation. If you need any further information please let me know thanks Barry

    Read the article

  • Custom model validation of dependent properties using Data Annotations

    - by Darin Dimitrov
    Since now I've used the excellent FluentValidation library to validate my model classes. In web applications I use it in conjunction with the jquery.validate plugin to perform client side validation as well. One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place. For this reason I'm looking for an alternative. There are many examples out there showing the usage of data annotations to perform model validation. It looks very promising. One thing I couldn't find out is how to validate a property that depends on another property value. Let's take for example the following model: public class Event { [Required] public DateTime? StartDate { get; set; } [Required] public DateTime? EndDate { get; set; } } I would like to ensure that EndDate is greater than StartDate. I could write a custom validation attribute extending ValidationAttribute in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the model instance: public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // value represents the property value on which this attribute is applied // but how to obtain the object instance to which this property belongs? return true; } } I found that the CustomValidationAttribute seems to do the job because it has this ValidationContext property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1? UPDATE: It seems that FluentValidation already supports clientside validation and metadata in ASP.NET MVC 2. Still it would be good to know though if data annotations could be used to validate dependent properties.

    Read the article

  • pass Validation error to UI element in WPF?

    - by Tony
    I am using IDataErrorInfo to validate my data in a form in WPF. I have the validation implemented in my presenter. The actual validation is happening, but the XAML that's supposed to update the UI and set the style isn't happening. Here it is: <Style x:Key="textBoxInError" TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> <Setter Property="Background" Value="Red"/> </Trigger> </Style.Triggers> </Style> The problem is that my binding to Validation.Errors contains no data. How do I get this data from the Presenter class and pass it to this XAML so as to update the UI elements? EDIT: Textbox: <TextBox Style="{StaticResource textBoxInError}" Name="txtAge" Height="23" Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" VerticalAlignment="Center" Width="150"> <TextBox.Text> <Binding Path="StrAge" Mode="TwoWay" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged"/> </TextBox.Text> The validation occurs, but the style to be applied when data is invalid is not happening.

    Read the article

  • Validation in n-tier asp.net mvc applications

    - by sTodorov
    Dear Stack Overflow gurus, I am looking for some practical/theoretical information regarding best practices for validation in asp.net mvc n-tier applications. I am working on a .Net application divided into the following layers: UI - Mvc3 BLL layer - all business rules. Decoupled from data access and UI layers through interfaces DAL layer - Data access with the repository pattern, EF4 and pocos Now, I am looking for a nice, clean and transparent way to specify my validation rules. Here are some thoughts on the matter so far: UI validation should only be responsible for user input and its validity. BLL validation should be handling the validity of the data regarding the application business rules. My main concern is how to bind the BLL and UI validation in the most efficient way. One think I am would like to avoid is having the UI check in a collection of validation and adding manually errors to the ModelState. Furthermore, I do not want to pass the ModelState to the BLL to be populated in there. I will appreciate any thoughts on the matter. P.S. Should this question be marked as a discussion ?

    Read the article

  • How do you reenable a validation control w/o it simultaneously performing an immediate validation?

    - by Velika2
    When I called this function to enable a validator from client javascript: `ValidatorEnable(document.getElementById('<%=valPassportOtherText.ClientID%>'), true); //enable` validation control the required validation control immediately performed it validation, found the value in the associated text box blank and set focus to the textbox (because SetFocusOnError was set to true). As a result, the side effect was that focus was shifted to the control that was associated with the Validation control, i teh example, txtSpecifyOccupation. <asp:TextBox ID="txtSpecifyOccupation" runat="server" AutoCompleteType="Disabled" CssClass="DefaultTextBox DefaultWidth" MaxLength="24" Rows="2"></asp:TextBox> <asp:RequiredFieldValidator ID="valSpecifyOccupation" runat="server" ControlToValidate="txtSpecifyOccupation" ErrorMessage="1.14b Please specify your &lt;b&gt;Occupation&lt;/b&gt;" SetFocusOnError="True">&nbsp;Required</asp:RequiredFieldValidator> Perhaps there is a way to enable the (required) validator without having it simultaneously perform the validation (at least until the user has tabbed off of it?) I'd like validation of the txtSpecifyOccupation textbox to occur only on a Page submit or when the user has tabbed of the required txtSpecifyoccupation textbox. How can I achieve this?

    Read the article

  • How do you reenable a validation control w/o it simultaneously perform an immediate validation?

    - by Velika2
    When I called this function to enable a validator from client javascript: `ValidatorEnable(document.getElementById('<%=valPassportOtherText.ClientID%>'), true); //enable` validation control the required validation control immediately performed it validation, found the value in the associated text box blank and set focus to the textbox (because SetFocusOnError was set to true). As a result, the side effect was that focus was shifted to the control that was associated with the Validation control, i teh example, txtSpecifyOccupation. <asp:TextBox ID="txtSpecifyOccupation" runat="server" AutoCompleteType="Disabled" CssClass="DefaultTextBox DefaultWidth" MaxLength="24" Rows="2"></asp:TextBox> <asp:RequiredFieldValidator ID="valSpecifyOccupation" runat="server" ControlToValidate="txtSpecifyOccupation" ErrorMessage="1.14b Please specify your &lt;b&gt;Occupation&lt;/b&gt;" SetFocusOnError="True">&nbsp;Required</asp:RequiredFieldValidator> Perhaps there is a way to enable the (required) validator without having it simultaneously perform the validation (at least until the user has tabbed off of it?) I'd like validation of the txtSpecifyOccupation textbox to occur only on a Page submit or when the user has tabbed of the required txtSpecifyoccupation textbox. How can I achieve this?

    Read the article

  • Custom model validation of dependent properties using Data Annotations

    - by Darin Dimitrov
    Since now I've used the excellent FluentValidation library to validate my model classes. In web applications I use it in conjunction with the jquery.validate plugin to perform client side validation as well. One drawback is that much of the validation logic is repeated on the client side and is no longer centralized at a single place. For this reason I'm looking for an alternative. There are many examples out there showing the usage of data annotations to perform model validation. It looks very promising. One thing I couldn't find out is how to validate a property that depends on another property value. Let's take for example the following model: public class Event { [Required] public DateTime? StartDate { get; set; } [Required] public DateTime? EndDate { get; set; } } I would like to ensure that EndDate is greater than StartDate. I could write a custom validation attribute extending ValidationAttribute in order to perform custom validation logic. Unfortunately I couldn't find a way to obtain the model instance: public class CustomValidationAttribute : ValidationAttribute { public override bool IsValid(object value) { // value represents the property value on which this attribute is applied // but how to obtain the object instance to which this property belongs? return true; } } I found that the CustomValidationAttribute seems to do the job because it has this ValidationContext property that contains the object instance being validated. Unfortunately this attribute has been added only in .NET 4.0. So my question is: can I achieve the same functionality in .NET 3.5 SP1? UPDATE: It seems that FluentValidation already supports clientside validation and metadata in ASP.NET MVC 2. Still it would be good to know though if data annotations could be used to validate dependent properties.

    Read the article

  • MVC + Is validation attributes enough?

    - by ebb
    My ViewModel has validation attributes that ensure that it wont be empty etc. - Is that enough or should I let my the code contracts I have made be in the ActionResult too? Example: // CreateCaseViewModel.cs public class CreateCaseViewModel { [Required] public string Topic { get; set; } [Required] public string Message { get; set; } } // CaseController.cs [AuthWhere(AuthorizeRole.Developer)] [HttpPost] public ActionResult Create(CreateCaseViewModel model) { if(!ModelState.IsValid) { // TODO: some cool stuff? } if (string.IsNullOrWhiteSpace(model.Message)) { throw new ArgumentException("Message cannot be null or empty", model.Message); } if (string.IsNullOrWhiteSpace(model.Topic)) { throw new ArgumentException("Topic cannot be null or empty", model.Topic); } var success = false; string message; var userId = new Guid(_membershipService.GetUserByUserName(User.Identity.Name).ProviderUserKey.ToString()); if(userId == Guid.Empty) { throw new ArgumentException("UserId cannot be empty"); } Case createCase = _caseService.CreateCase(model.Topic, model.Message); if(createCase == null) { throw new ArgumentException("Case cannot be null"); } if(_caseService.AddCase(createCase, userId)) { message = ControllerResources.CaseCreateFail; } else { success = true; message = ControllerResources.CaseCreateSuccess; } return Json(new { Success = success, Message = message, Partial = RenderPartialViewToString(ListView, GetCases) }); }

    Read the article

  • wordpress add post validation

    - by dskanth
    This is embarrassing, but yet i am surprised to see that there is no validation by default while adding a new post in wordpress. When i don't enter a title and even content, and just hit Publish, it says that the post is published, and when i view the front end, there is no new post. How could wordpress skip the simple validation for adding a post? Atleast i expected a server side validation (if not client side). Don't know why the validation is skipped. It is upto wordpress, whether they incorporate it in the new versions. But i want to know how can i add a javascript (or jquery) validation for adding a post in wordpress. I know it must not at all be difficult. But being new to wordpress, i would like to get some hint. From Firebug, i could see the form is rendering like: <form id="post" method="post" action="post.php" name="post"> ... </form> Where shall i put my javascript validation code?

    Read the article

  • How to create a link to Nintex Start Workflow Page in the document set home page

    - by ybbest
    In this blog post, I’d like to show you how to create a link to start Nintex Workflow Page in the document set home page. 1. Firstly, you need to upload the latest version of jQuery to the style library of your team site. 2. Then, upload a text file to the style library for writing your own html and JavaScript 3. In the document set home page, insert a new content editor web part and link the text file you just upload. 4. Update the text file with the following content, you can download this file here. <script type="text/javascript" src="/Style%20Library/jquery-1.9.0.min.js"></script> <script type="text/javascript" src="/_layouts/sp.js"></script> <script type="text/javascript"> $(document).ready(function() { listItemId=getParameterByName("ID"); setTheWorkflowLink("YBBESTDocumentLibrary"); }); function buildWorkflowLink(webRelativeUrl,listId,itemId) { var workflowLink =webRelativeUrl+"_layouts/NintexWorkflow/StartWorkflow.aspx?list="+listId+"&ID="+itemId+"&WorkflowName=Start Approval"; return workflowLink; } function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regexS = "[\\?&]" + name + "=([^&#]*)"; var regex = new RegExp(regexS); var results = regex.exec(window.location.search); if(results == null){ return ""; } else{ return decodeURIComponent(results[1].replace(/\+/g, " ")); } } function setTheWorkflowLink(listName) { var SPContext = new SP.ClientContext.get_current(); web = SPContext.get_web(); list = web.get_lists().getByTitle(listName); SPContext.load(web,"ServerRelativeUrl"); SPContext.load(list, 'Title', 'Id'); SPContext.executeQueryAsync(setTheWorkflowLink_Success, setTheWorkflowLink_Fail); } function setTheWorkflowLink_Success(sender, args) { var listId = list.get_id(); var listTitle = list.get_title(); var webRelativeUrl = web.get_serverRelativeUrl(); var startWorkflowLink=buildWorkflowLink(webRelativeUrl,listId,listItemId) $("a#submitLink").attr('href',startWorkflowLink); } function setTheWorkflowLink_Fail(sender, args) { alert("There is a problem setting up the submit exam approval link"); } </script> <a href="" target="_blank" id="submitLink"><span style="font-size:14pt">Start the approval process.</span></a> 5. Save your changes and go to the document set Item, you will see the link is on the home page now. Notes: 1. You can create a link to start the workflow using the following build dynamic string configuration: {Common:WebUrl}/_layouts/NintexWorkflow/StartWorkflow.aspx?list={Common:ListID}&ID={ItemProperty:ID}&WorkflowName=workflowname. With this link you will still need to click the start button, this is standard SharePoint behaviour and cannot be altered. References: http://connect.nintex.com/forums/27143/ShowThread.aspx How to use html and JavaScript in Content Editor web part in SharePoint2010

    Read the article

  • MVC 3 Remote Validation jQuery error on submit

    - by Richard Reddy
    I seem to have a weird issue with remote validation on my project. I am doing a simple validation check on an email field to ensure that it is unique. I've noticed that unless I put the cursor into the textbox and then remove it to trigger the validation at least once before submitting my form I will get a javascript error. e[h] is not a function jquery.min.js line 3 If I try to resubmit the form after the above error is returned everything works as expected. It's almost like the form tried to submit before waiting for the validation to return or something. Am I required to silently fire off a remote validation request on submit before submitting my form? Below is a snapshot of the code I'm using: (I've also tried GET instead of POST but I get the same result). As mentioned above, the code works fine but the form returns a jquery error unless the validation is triggered at least once. Model: public class RegisterModel { [Required] [Remote("DoesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name taken.")] [Display(Name = "User name")] public string UserName { get; set; } [Required] [Display(Name = "Firstname")] public string Firstname { get; set; } [Display(Name = "Surname")] public string Surname { get; set; } [Required] [Remote("DoesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "Email taken.", AdditionalFields = "UserName")] [Display(Name = "Email address")] public string Email { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)] [DataType(DataType.Password)] [Display(Name = "Confirm password")] public string ConfirmPassword { get; set; } [Display(Name = "Approved?")] public bool IsApproved { get; set; } } public class UserRoleModel { [Display(Name = "Assign Roles")] public IEnumerable<RoleViewModel> AllRoles { get; set; } public RegisterModel RegisterUser { get; set; } } Controller: // POST: /Account/DoesEmailExist // passing in username so that I can ignore the same email address for the same user on edit page [HttpPost] public JsonResult DoesEmailExist([Bind(Prefix = "RegisterUser.Email")]string Email, [Bind(Prefix = "RegisterUser.UserName")]string UserName) { var user = Membership.GetUserNameByEmail(Email); if (!String.IsNullOrEmpty(UserName)) { if (user == UserName) return Json(true); } return Json(user == null); } View: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/jquery-ui.min.js" type="text/javascript"></script> <script type="text/javascript" src="/Content/web/js/jquery.unobtrusive-ajax.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.min.js"></script> <script type="text/javascript" src="/Content/web/js/jquery.validate.unobtrusive.min.js"></script> ...... @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="titleh"> <h3>Edit a user account</h3> </div> <div class="body"> @Html.HiddenFor(model => model.RegisterUser.UserName) @Html.Partial("_CreateOrEdit", Model) <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(model => model.RegisterUser.IsApproved)</span> @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, true, new { @class = "uniform" }) Active @Html.RadioButtonFor(model => model.RegisterUser.IsApproved, false, new { @class = "uniform" }) Disabled <div class="clear"></div> </div> <div class="button-box"> <input type="submit" name="submit" value="Save" class="st-button"/> @Html.ActionLink("Back to List", "Index", null, new { @class = "st-clear" }) </div> </div> } CreateEdit Partial View @model Project.Domain.Entities.UserRoleModel <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Firstname)</span> @Html.TextBoxFor(m => m.RegisterUser.Firstname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Firstname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Surname)</span> @Html.TextBoxFor(m => m.RegisterUser.Surname, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Surname) <div class="clear"></div> </div> <div class="st-form-line"> <span class="st-labeltext">@Html.LabelFor(m => m.RegisterUser.Email)</span> @Html.TextBoxFor(m => m.RegisterUser.Email, new { @class = "st-forminput", @style = "width:300px" }) @Html.ValidationMessageFor(m => m.RegisterUser.Email) <div class="clear"></div> </div> Thanks, Rich

    Read the article

  • MVC 2 Entity Framework View Model Insert

    - by cannibalcorpse
    This is driving me crazy. Hopefully my question makes sense... I'm using MVC 2 and Entity Framework 1 and am trying to insert a new record with two navigation properties. I have a SQL table, Categories, that has a lookup table CategoryTypes and another self-referencing lookup CategoryParent. EF makes two nav properties on my Category model, one called Parent and another called CategoryType, both instances of their respective models. On my view that creates the new Category, I have two dropdowns, one for the CategoryType and another for the ParentCategory. When I try and insert the new Category WITHOUT the ParentCategory, which allows nulls, everything is fine. As soon as I add the ParentCategory, the insert fails, and oddly (or so I think) complains about the CategoryType in the form of this error: 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. When I step through, I can verifiy that both ID properties coming in on the action method parameter are correct. I can also verify that when I go to the db to get the CategoryType and ParentCategory with the ID's, the records are being pulled fine. Yet it fails on SaveChanges(). All that I can see is that my CategoryParent dropdownlistfor in my view, is somehow causing the insert to bomb. Please see my comments in my httpPost Create action method. My view model looks like this: public class EditModel { public Category MainCategory { get; set; } public IEnumerable<CategoryType> CategoryTypesList { get; set; } public IEnumerable<Category> ParentCategoriesList { get; set; } } My Create action methods look like this: // GET: /Categories/Create public ActionResult Create() { return View(new EditModel() { CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); } // POST: /Categories/Create [HttpPost] public ActionResult Create(Category mainCategory) { if (!ModelState.IsValid) return View(new EditModel() { MainCategory = mainCategory, CategoryTypesList = _db.CategoryTypeSet.ToList(), ParentCategoriesList = _db.CategorySet.ToList() }); mainCategory.CategoryType = _db.CategoryTypeSet.First(ct => ct.Id == mainCategory.CategoryType.Id); // This db call DOES get the correct Category, but fails on _db.SaveChanges(). // Oddly the error is related to CategoryTypes and not Category. // Entities in 'DbEntities.CategorySet' participate in the 'FK_Categories_CategoryTypes' relationship. // 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected. //mainCategory.Parent = _db.CategorySet.First(c => c.Id == mainCategory.Parent.Id); // If I just use the literal ID of the same Category, // AND comment out the CategoryParent dropdownlistfor in the view, all is fine. mainCategory.Parent = _db.CategorySet.First(c => c.Id == 2); _db.AddToCategorySet(mainCategory); _db.SaveChanges(); return RedirectToAction("Index"); } Here is my Create form on the view : <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div> <%= Html.LabelFor(model => model.MainCategory.Parent.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.Parent.Id, new SelectList(Model.ParentCategoriesList, "Id", "Name")) %> <%= Html.ValidationMessageFor(model => model.MainCategory.Parent.Id) %> </div> <div> <%= Html.LabelFor(model => model.MainCategory.CategoryType.Id) %> <%= Html.DropDownListFor(model => model.MainCategory.CategoryType.Id, new SelectList(Model.CategoryTypesList, "Id", "Name"))%> <%= Html.ValidationMessageFor(model => model.MainCategory.CategoryType.Id)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Name) %> <%= Html.TextBoxFor(model => model.MainCategory.Name)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Name)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.Description)%> <%= Html.TextAreaFor(model => model.MainCategory.Description)%> <%= Html.ValidationMessageFor(model => model.MainCategory.Description)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.SeoName)%> <%= Html.TextBoxFor(model => model.MainCategory.SeoName, new { @class = "large" })%> <%= Html.ValidationMessageFor(model => model.MainCategory.SeoName)%> </div> <div> <%= Html.LabelFor(model => model.MainCategory.HasHomepage)%> <%= Html.CheckBoxFor(model => model.MainCategory.HasHomepage)%> <%= Html.ValidationMessageFor(model => model.MainCategory.HasHomepage)%> </div> <p><input type="submit" value="Create" /></p> </fieldset> <% } %> Maybe I've just been staying up too late playing with MVC 2? :) Please let me know if I'm not being clear enough.

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >