How can I make the Required attribute for my custom DropDownList editor template operate client side?
Asked Answered
L

2

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.

Labuan answered 15/1, 2013 at 14:5 Comment(3)
Could you add code of your modelWorldshaking
@SławomirRosiek What is that supposed to mean? This is a general question applies to any model.Labuan
For me it works - did you have problem only with that control or maybe with all client-side validators?Worldshaking
S
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:

    <appSettings>
    <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 - ")
    
Semiliquid answered 17/1, 2013 at 18:14 Comment(2)
All my other client side validation works. My problem is that only my DropDownList editor template doesn't validate client side.Labuan
I added another possibility.Worldshaking
C
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?

Charactery answered 18/1, 2013 at 11:15 Comment(1)
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.Labuan

© 2022 - 2024 — McMap. All rights reserved.