Search code examples
c#-4.0required-fielddata-annotations

asp.net mvc override dataannotations in strongly typed view


I have a customer object

 [StringLength(50)]
        [Display(Name="First Name")]
        [Required(ErrorMessage = "Required")]
        [RegularExpression("([a-zA-Z]+)", ErrorMessage = "only alphabets allowed")]
        public new string FirstName { get; set; }

        [StringLength(50)]        
        [Display(Name = "Last Name")]
        [Required(ErrorMessage = "Required")]
        [RegularExpression("([a-zA-Z]+)", ErrorMessage = "only alphabets allowed")]
        public new string LastName { get; set; }

I am using this object in "Add" view and "Search" view

view:

 <li>
                     @Html.LabelFor(x=>x.FirstName)
                        @Html.TextBoxFor(x => x.FirstName, new { required=false })
                    </li>

                    <li>
                          @Html.LabelFor(x=>x.LastName)
                        @Html.TextBoxFor(x => x.LastName, new { required=false })
                    </li>

In add view i want all dataannotations properties to work. and it is doing accordingly. But in my "search" view I don't want the fields to be required. rest of the data annotation can stay.

Is this possible?


Solution

  • Well. this is how i handled it in my case. instead of creating a new ViewModel I have added a class to all my forms as SearchForm and using JavaScript I have removed all required attributes for it.

    //Clear Form Required stuff for search
    $(function () {
        $(".SearchForm").find("input:text").each(function () {
            $(this).removeAttr("data-val-required");
        });
        $(".SearchForm").find("select").each(function () {
            $(this).removeAttr("data-val-required");
        });
    });