0

I know I can make DropDownListFor required in HTML page by adding required felid as below:

@Html.DropDownListFor(m => m.Site_idSite, Model.GetSiteList(Model.idCompany),  new { @class = "w_300p", required = "required" })

My question is how can I make ListBoxFor required?

@Html.ListBoxFor(m => m.SelectedSites, Model.GetSiteList(Model.idCompany), new { @class = "w_250p", Size = "4" })

Any help will be appreciated. Stuck with this problem quite a longg.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • you need custom validator see : https://stackoverflow.com/questions/6428907/required-attribute-on-generic-list-property – Ehsan Sajjad Jun 12 '17 at 01:13
  • `required = "required"` is HTML5 validation and is client side only - you must always validate on the server. Use a `[Required]` attribute in conjunction with `@Html.ValidationMessageFor()` for the `Site_idSite` property. For `SelectedSites` you need to write a custom validation attribute that implements `IClientValidatable` (the link above is server side only) –  Jun 12 '17 at 02:21
  • did you solve question? – hasan Jun 13 '17 at 22:29
  • nope. Actually you can achieve this if you mark required in model for that particular view. Whereas My requirement is I have to mark that as required only if it satisfied the if condition so I can mark [required] in model. – Gagandeep Singh Randhawa Jun 15 '17 at 18:20

2 Answers2

0

Can you try this for server side validation

public class ProgramViewModel
    {
        [Required(ErrorMessage = "Please select at least one company")]
        public IEnumerable<string> YourCompanyIdList{ get; set; }
    }

and also if you want to enable client side validation you can use this reference: https://www.codeproject.com/Articles/718004/ASP-NET-MVC-Client-Side-Validation

hasan
  • 3,484
  • 1
  • 16
  • 23
0

How about this ?

@Html.ListBoxFor(m => m.SelectedSites, Model.GetSiteList(Model.idCompany), new { @class = "w_250p", Size = "4", @required = "required" })