8

I'm using ASP.Net MVC 3 . I've an entity called Student having the properties Id, Name, Age, RollNo. In the create page of Student, I've used validation framework. But in Advanced Search page I'm using all the properties but don't want to use validation framework as users may not want to use all the fields for searching.

I would also like to mention that I've used [Required] annotation in model class.

Please help me to overcome this issue.

Regards Molay

2
  • use Html.TextBox instead? You will lose other goodness which TextBoxFor brings but they are not so hard to hardcode. Commented Dec 21, 2011 at 9:04
  • When you feel like that, then you suppose to consider ViewModel for this search page or any other custom page. After all ViewModels is always a best practice. Commented Dec 21, 2011 at 10:16

5 Answers 5

17

I would agree with xixonia, use a separate View Model for search but to answer your question you have a few options client side:

  1. Pass in data-val = "false" as an HTML attribute, e.g: @Html.TextBoxFor(x => x.Age, new { data_val = "false" });
  2. Use @Html.TextBox() instead
  3. Manually create your text box with HTML using the same input name so it binds to the model

If you're doing validation in the back end (you should be!), i.e. checking ModelState.IsValid then you will have to remove the validation properties from the ModelState, like so: ModelState.Remove("Age");.

Sign up to request clarification or add additional context in comments.

1 Comment

I didn't think about doing that! :)
3

Add this code on your form:

@Html.EnableClientValidation(false);

Comments

2

You can not remove attribute at run-time. You will have to have multiple view-models for student entity one for create and other for search.

Comments

2

It sounds like the values of the Student class are restricted (as they should be).

I would consider using a separate view model for the search, rather than using a Student.

public class Student
{
    [ValidationAttributeOfSomeKind]
    int Age { get; set; }

    [ValidationAttributeOfSomeKind]
    string Name { get; set; }
}

public class StudentSearch
{
    int? Age { get; set; }

    string Name { get; set; }
}

Comments

1

I think you have to write your own textbox helper. There is no way to disable this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.