Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7058319
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T04:05:55+00:00 2026-05-28T04:05:55+00:00

I have the following view models: public class Search { public int Id {

  • 0

I have the following view models:

public class Search {
    public int Id { get; set; }

    [Required(ErrorMessage = "Please choose a name.")]
    public string Name { get; set; }

    [ValidGroup(ErrorMessage = "Please create a new group or choose an existing one.")]
    public Group Group { get; set; }
}

public class Group {
    public int Id { get; set; }
    public string Name { get; set; }
}

I have defined a custom validation attribute as follows:

public class ValidGroupAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null)
            return false;

        Group group = (Group)value;

        return !(string.IsNullOrEmpty(group.Name) && group.Id == 0);
    }
}

I have the following view (omitted some for brevity):

    @Html.ValidationSummary()

    <p>
        <!-- These are custom HTML helper extensions. -->
        @Html.RadioButtonForBool(m => m.NewGroup, true, "New", new { @class = "formRadioSearch", id = "NewGroup" })
        @Html.RadioButtonForBool(m => m.NewGroup, false, "Existing", new { @class = "formRadioSearch", id = "ExistingGroup" })
    </p>
    <p>
        <label>Group</label>
        @if (Model.Group != null && Model.Group.Id == 0) {
            @Html.TextBoxFor(m => m.Group.Name)
        }
        else {
            @Html.DropDownListFor(m => m.Group.Id, Model.Groups)
        }
    </p>

The issue I’m having is the validation class input-validation-error does not get applied to the Group input. I assume this is because the framework is trying to find a field with id="Group" and the markup that is being generated has either id="Group_Id" or id=Group_Name. Is there a way I can get the class applied?

http://f.cl.ly/items/0Y3R0W3Z193s3d1h3518/Capture.PNG

Update

I’ve tried implementing IValidatableObject on the Group view model instead of using a validation attribute but I still can’t get the CSS class to apply:

public class Group : IValidatableObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (string.IsNullOrEmpty(Name) && Id == 0) {
            yield return new ValidationResult("Please create a new group or select an existing one.", new[] { "Group.Name" });
        }
    }
}

Update 2

Self validation doesn’t work. I think this is because the second parameter in the ValidationResult constructor isn’t used in the MVC framework.

From: http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

In some situations, you might be tempted to use the second constructor overload of ValidationResult that takes in an IEnumerable of member names. For example, you may decide that you want to display the error message on both fields being compared, so you change the code to this:

return new ValidationResult(
FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName, OtherProperty });

If you run your code, you will find absolutely no difference. This is because although this overload is present and presumably used elsewhere in the .NET framework, the MVC framework completely ignores ValidationResult.MemberNames.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T04:05:55+00:00Added an answer on May 28, 2026 at 4:05 am

    I’ve come up with a solution that works but is clearly a work around.

    I’ve removed the validation attribute and created a custom model binder instead which manually adds an error to the ModelState dictionary for the property Group.Name.

    public class SearchBinder : DefaultModelBinder {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
           PropertyDescriptor propertyDescriptor) {
            if (propertyDescriptor.Name == "Group" &&
                bindingContext.ValueProvider.GetValue("Group.Name") != null &&
                bindingContext.ValueProvider.GetValue("Group.Name").AttemptedValue == "") {
                ModelState modelState = new ModelState { Value = bindingContext.ValueProvider.GetValue("Group.Name") };
                modelState.Errors.Add("Please create a new group or choose an existing one.");
                bindingContext.ModelState.Add("Group.Name", modelState);
            }
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }
    
    // Register custom model binders in Application_Start()
    ModelBinders.Binders.Add(typeof(SearchViewModel), new SearchBinder());
    

    With ModelState["Group.Name"] now having an error entry, the CSS class is being rendered in the markup.

    I would much prefer if there was a way to do this with idiomatic validation in MVC though.

    Solved!

    Found a proper way to do this. I was specifying the wrong property name in the self validating class, so the key that was being added to the ModelState dictionary was Group.Group.Name. All I had to do was change the returned ValidationResult.

    yield return new ValidationResult("Please create a new group or select an existing one.", new[] { "Name" });
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Say I have the following models: public class Item { public int Id{ get;
I have following ViewModel: public class Bulletin1ViewModel { [Required] public String NumberDelegations { get;
Given the following Model, public class A { public string Name { get; set;
I have the following model, view and controller. Model public class Person { public
I have the following ViewModel public class RecommendationModel { public List<CheckBoxItem> CheckBoxList { get;
I have the following model : public class Foo { [Key] public int FooID
I have the following models: class A { // ...some properties public B InnerField
I have a custom class: public class Person { public String Name { get;
I have the following ViewModel: public class AllQuestionsInCategoriesViewModel { public string Category_Name { get;
I have the following class: namespace Storage.Models { public class AdminDetail { public string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.