Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 410
ProfK Avatar asked Jan 15 '13 14:01

ProfK


1 Answers

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 - ")
    
like image 141
Sławomir Rosiek Avatar answered Nov 02 '22 14:11

Sławomir Rosiek