[RESOLVED]Validator for HTML Helper ListBoxFor( )

Hello,

How to validate a html helper listbox using model binding ?

MODEL:

 public class ParentModel
    {        
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    } 

public class FileUploadModel
    {        
        [Required, Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }  
    }
    public class ProgramViewModel
    {        
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

Controller:

 [HttpPost]
        public ActionResult AuxiliaryProgramMapping(ParentModel model)
        {
            if (ModelState.IsValid)
            {                
                bool isCheckedForAllPrograms =model.FileUploadModel.IsAllPrograms;
                var AuxProgramName = model.FileUploadModel.AuxiliaryState;

                IEnumerable<string> selectedPrograms = model.ProgramViewModel.SelectedPrograms;
                if (selectedPrograms == null)
                {
                       // something
                }
                else
                 {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("You selected – " + string.Join(",", selectedPrograms));
                    string x = sb.ToString();
                 }



                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;

                string path = @"D:Temp";

                HttpPostedFileBase photoa = model.FileUploadModel.File;
                if (photoa != null)
                    photoa.SaveAs(path + photoa.FileName);
                return View(parent);

            }
            else
            {
                List<SelectListItem> listSelectListItems = new List<SelectListItem>();
                List<AdminDTO> lll = objAdminBussinessLayer.GetActivePrograms();
                foreach (var programs in lll)
                {
                    SelectListItem selectList = new SelectListItem()
                    {
                        Text = programs.ProgramName,
                        Value = Convert.ToString(programs.ProgramID)
                    };
                    listSelectListItems.Add(selectList);
                }
                ProgramViewModel ProgramsViewModel = new ProgramViewModel()
                {
                    Programs = listSelectListItems
                };

                ParentModel parent = new ParentModel();
                parent.ProgramViewModel = ProgramsViewModel;
                return View(parent);
            }
        }

VIEW:

@using (Html.BeginForm("AuxiliaryProgramMapping", "AuxiliaryProgramMapping", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
               ... blah blah 

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                               
 @* Now how to validate this listbox .. (required)*@
               ... blah blah
             }

 

Hi did you try  this ?

@Html.ValidationMessageFor(model => model.YourModel, "", new { @class = "text-danger" })

i would gladly do that , but the problem is WHERE shall i mention the Required attribute ?

i did like below : but couldnt make it work.

 public class ProgramViewModel
    {
        [Required(ErrorMessage = "Please select atleast one program")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }


 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

to make it easy why don’t you just try to use this?

http://jqueryvalidation.org/required-method/ 

M afraid i cant do that , requirement is like this only , i cant do validations from jquery i need to do that using model binding only.

Anyone ???

Hi Ashim,

For this requirement, you need to custom validation.

There are some links that can help you:

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

Best Regards

Starain

Starain chen – MSFT

# Custom Unobtrusive jQuery Validation with Data Annotations

http://thewayofcode.wordpress.com/2012/01/18/custom-unobtrusive-jquery-validation-with-data-annotations-in-mvc-3/

Thats a good example to override the isvalid method , but the the thing is m new to MVC and i really dont have any idea about how to do custom validation on a listboxfor helper ? Can you please help me out ?

# Required Attribute on Generic List Property

http://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property

This is custom validation on whether the generic list is empty or not , my question is whether the list have any selected item or not ? both are different. 

Hi Ashim,

You could refer to the first link to learn how to custom validation and the second link is the sample about how to check whether the collection is empty or not.

For the form submit, it just sends the selected items data instead of all items. So you just need to check whether the collection has data or not.

Best Regards

Starain

Starain chen – MSFT

So you just need to check whether the collection has data or not.

I tried , but its not working : see this:

MODEL:

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
    public class IsSelectedAttribute : ValidationAttribute
    {
        public IsSelectedAttribute(string errorMessage) : base(errorMessage)
        {
            this.ErrorMessage = errorMessage;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            ValidationResult validationResult = ValidationResult.Success;
            try
            {
                if(value == null)
                {
                    validationResult = new ValidationResult(ErrorMessageString);
                }                
            }
            catch (Exception ex)
            {
                // Do stuff, i.e. log the exception
                // Let it go through the upper levels, something bad happened
                throw ex;
            }

            return validationResult;
        }
    }
    public class ParentModel
    {
        public AuxiliaryProgramMappingDTO AuxiliaryProgramMappingDTO { get; set; }
        public FileUploadModel FileUploadModel { get; set; }
        public ProgramViewModel ProgramViewModel { get; set; }
    }    
    public class FileUploadModel
    {        
        [Required(ErrorMessage="Please upload an icon"), Microsoft.Web.Mvc.FileExtensions(Extensions = "jpg", ErrorMessage = "please specify a jpg file only.")]
        [DisplayName("FileName")]
        public HttpPostedFileBase File { get; set; }

        [Required(AllowEmptyStrings=false,ErrorMessage = "Please add an auxiliary state")]
        [MaxLength(100, ErrorMessage = "AuxiliaryState should not be longer than 100 characters.")]
        [DisplayName("AuxiliaryState")]
        public string AuxiliaryState { get; set; }

        public bool IsAllPrograms { get; set; }
    }
    public class ProgramViewModel
    {   
        [IsSelected("Please select atleast one program.")]
        public IEnumerable<string> SelectedPrograms { get; set; }
        public IEnumerable<SelectListItem> Programs { get; set; }
    }

VIEW:

 @Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms) 

After this in Controller when i try to check whether ModelState is valid.Its showing valid ,when it should not.Please recreate the scenario at your end.

Ashim Chatterjee

Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new { @class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
 @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

           Html.ListBoxFor(model => model.ProgramViewModel.SelectedPrograms, Model.ProgramViewModel.Programs, new {  required="required",@class = "select2-me input-block-level",@size="10", data_placeholder = "Select one or more program(s)."})
                @Html.ValidationMessageFor(model => model.ProgramViewModel.SelectedPrograms)

add required="required"  attribute to the listbox

cnuonline

add required="required"  attribute to the listbox

You are a life saver … cheers. 

Thanks  a lot. :)

cnuonline

add required="required"  attribute to the listbox

Just One Question : can i add my own error message instead of the default one ?

try this

document.getElementById('ProgramViewModel_SelectedPrograms').setCustomValidity('Please select  a Programs');

where shall i call that .. i tried in document ready , didnt worked .

Is this a main view or a partial view loading after document load?

this is a main view.

Make sure the id of the list box in the statement

Thanks .. :)

Leave a Reply