开发者

ASP.Net MVC 3 unobtrusive client validation does not work with drop down lists

开发者 https://www.devze.com 2023-02-06 13:53 出处:网络
I have a simple drop down list, the first item in the list has an empty value. If I do not select anything in the list the client validation ignores it. I have that field set up as required on the mod

I have a simple drop down list, the first item in the list has an empty value. If I do not select anything in the list the client validation ignores it. I have that field set up as required on the model using annotation attributes.

 @Html.DropDownListFor(model => 开发者_开发问答Model.CCPayment.State, UnitedStatesStates.StateSelectList)



[Required(ErrorMessage = "State is Required.")]
    public string State
    {
        get
        {
            return _state;
        }
        set
        {
            _state = value;
        }
    }

any ideas? am I missing something?


It looks like a legitimate bug, here's the best workaround I've found in my search:

http://forums.asp.net/t/1649193.aspx

In short. You wrap the source of the problem, DropDownListFor, in a custom Html extension and you manually retrieve the unobtrusive clientside validation rules like this:

IDictionary<string, object> validationAttributes = htmlHelper.
    GetUnobtrusiveValidationAttributes(
        ExpressionHelper.GetExpressionText(expression),
        metadata
    );

Then you combine your validationAttributes dictionary with any other html attributes passed into your custom helper and you pass that along to DropDownListFor

The complete code that I'm using (I have a label in there too, you can feel free to de-couple):

public static IHtmlString DropDownListWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string label, IEnumerable<SelectListItem> items, string blankOption, object htmlAttributes = null)
{
    var l = new TagBuilder("label");
    var br = new TagBuilder("br");

    var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    var mergedAttributes = helper.GetUnobtrusiveValidationAttributes(ExpressionHelper.GetExpressionText(expression), metadata);

    if (htmlAttributes != null)
    {
        foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(htmlAttributes))
        {
            object value = descriptor.GetValue(htmlAttributes);
            mergedAttributes.Add(descriptor.Name, value);
        }
    }

    l.InnerHtml = label + br.ToString(TagRenderMode.SelfClosing) + helper.DropDownListFor(expression, items, blankOption, mergedAttributes);
    return MvcHtmlString.Create(l.ToString(TagRenderMode.Normal));
}


You have provided too little information in order for us to be able to pinpoint the problem. You might have forgot to include the proper unobtrusive validation scripts inside your view but who knows? You haven't shown your view.

Here's a full working example:

Model:

public class MyViewModel
{
    [Required(ErrorMessage = "State is Required.")]
    public string State { get; set; }

    public IEnumerable<SelectListItem> States 
    { 
        get
        {
            return Enumerable.Range(1, 5).Select(x => new SelectListItem
            {
                Value = x.ToString(),
                Text = "state " + x
            });
        }
    }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model AppName.Models.MyViewModel
@{
    ViewBag.Title = "Home Page";
}
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.State)
    @Html.DropDownListFor(
        x => x.State, 
        new SelectList(Model.States, "Value", "Text"), 
        "-- Please select a state --"
    )
    @Html.ValidationMessageFor(x => x.State)
    <input type="submit" value="OK" />
}

Notice how we are providing a default value in the DropDownListFor helper as last parameter. That will insert an option in the beginning with empty value and custom text and if the user doesn't pick some state the required validator should kick in.


I added @class="required" to the attributes like some guy said on the thread at codeplex http://aspnet.codeplex.com/workitem/7629 and it worked fine for me =)


This is the simpliest way I found to do it, just adding data-val-*-* attributes in HtmlAttributes of DropDownListFor, inside the view. The following method works with RemoteValidation too, if you do not need remote validation, simply remove the elements containing data-val-remote-*:

        @Html.DropDownListFor(m => m.yourlistID, (IEnumerable<SelectListItem>)ViewBag.YourListID, String.Empty, 
        new Dictionary<string, object>() { { "data-val", "true" }, 
        { "data-val-remote-url", "/Validation/yourremoteval" }, 
        { "data-val-remote-type", "POST" }, { "data-val-remote-additionalfield", "youradditionalfieldtovalidate" } })

I hope it may help. Best Regards!


If the issue is that when you select the 'blank' option, you are not seeing the validation message saying the field is required, it's probably because of how the Html Helper generates the option tag for the 'blank' option. The problem is the empty value attribute.

<select ...>
  <option value="">
  ...
</select>

I used this one-line workaround to remove the value attribute, and it worked like a charm!

$('option[value=""]').removeAttr("value");

All this does is remove the value attribute from any 'option' element with a blank value attribute.

0

精彩评论

暂无评论...
验证码 换一张
取 消