9

I have an editor template for DropDownLists that is marked with an attribute like this:

[AttributeUsage(AttributeTargets.Property)]
public class DropDownListAttribute : UIHintAttribute
{
    public string SelectListName { get; set; }
    public DropDownListAttribute(string selectListName)
        : base("DropDownList", "MVC", selectListName)
    {
        SelectListName = selectListName;
    }
}

And itself looks like this:

@using Comair.RI.UI.Core
@{
    var list = this.GetModelSelectList();
    var listWithSelected = new SelectList(list.Items, list.DataValueField, list.DataTextField, Model);
}
@Html.DropDownListFor(m => Model, listWithSelected, " - select - ")

My issue here is it only validates server side, which is very annoying for a user to resolve all client side validations, only to submit and get a new, surprise server side validation.

Dismissile
  • 32,564
  • 38
  • 174
  • 263
ProfK
  • 49,207
  • 121
  • 399
  • 775

2 Answers2

1

If your client side validation doesn't work it may be caused by one of the following reasons:

  1. Your web.config doesn't have that enteries:

    &ltappSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    
  2. You forgotten to add validation scripts:

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
    
  3. Your controls are not surrounded by Html.BeginForm or Ajax.BeginForm

  4. Client-side validation can stop working in EditorFor after update to ASP.NET MVC 4 if you use:

    @Html.DropDownListFor(m => Model, listWithSelected, " - select - ")
    

    Replacing Model with m should resolve problem:

    @Html.DropDownListFor(m => m, listWithSelected, " - select - ")
    
Sławomir Rosiek
  • 4,038
  • 3
  • 25
  • 43
0

Set the required class

@Html.DropDownListFor(m => Model, listWithSelected, " - select - ", new { @class='required' })

See ASP MVC 3: How can I do Client side Validation on a Select List?

Community
  • 1
  • 1
Jeroen K
  • 10,258
  • 5
  • 41
  • 40
  • Lovely, except the default message is just "This field is required." not the "The {0} field is required." Find if you place validation messages inline, but not so cool if you group them in some 'window' somewhere. – ProfK Jan 19 '13 at 16:29