为什么这个下拉列表无法验证客户端?

时间:2017-05-16 14:59:15

标签: asp.net .net asp.net-mvc validation

在这个例子中,我有一个汽车模型,我想指定' make'有下拉的汽车。 A' make'是必需的。

我在web.config中启用了clientide验证:

 <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>

我有设置&#39; make&#39;汽车模型中要求的财产:

 public class car
    {
        public int carId { get; set; }

        [Required]
        public int makeId { get; set; }

        virtual public make make { get; set; }

        [Required]
        public string carModel { get; set; }
    }

    public class make {

        public int makeId { get; set; }

        [Required]
        public string  makeName { get; set; }

    }

视图中引用了JQuery验证,但只有在提交表单时才会验证下拉列表吗?

@model validation.Models.car

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>car</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.makeId, "makeId", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("makeId", null, "--Select--", htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.makeId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.carModel, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.carModel, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.carModel, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

如果我关闭UnobtrusiveJavaScript,那么carcodel&#39;或者&#39;制作&#39;验证客户端,都只验证服务器端。

 <add key="UnobtrusiveJavaScriptEnabled" value="false" />

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决方案:how to validate dropdownlist using the DataAnnotation?

我使用了DropDownListFor助手而不是DropDownList。现在,下拉菜单验证了客户端。

@Html.DropDownListFor(model => model.makeId, ViewBag.makes as IEnumerable<SelectListItem>, "-- Select --", htmlAttributes: new { @class = "form-control" })

我不完全确定为什么这会解决这个问题,如果有人可以解决问题呢?