客户端验证不适用于razor MVC3中的DropDownListFor?

时间:2012-07-30 13:10:07

标签: asp.net-mvc-3

当我单击按钮时,客户端验证不起作用,下面是我的视图和模型

视图:

 <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("Guestlogin", "Home", FormMethod.Post))
            {
                for (int i =0; i <1; i++)
                {
             @Html.DropDownListFor(per => per.[i].Gender, new[] {
                                            new SelectListItem(){Text = "Male" , Value="Male"},
                                            new SelectListItem(){Text ="Female" , Value = "Female"},
                                        }, "Select Your Gender")@Html.ValidationMessageFor(o => o[i].Gender)
            }

            <button type="submit" name="Button"/>
            }

模型:

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

2 个答案:

答案 0 :(得分:1)

检查你的模特:

public class urvalidationmodel
{
    [Required]
    [Display(Name = "Gender")]
    public IEnumerable<Gender> gender { get; set; }
}

是:

function Gender(sender, args) {
    var v = document.getElementById('Gender').value;
    if (v == 'Male' || v == 'Female') {
        args.IsValid = true; // Valid
    }
    else {
        args.IsValid = false; // Invalid
    }
}

答案 1 :(得分:0)

只需在表单前的视图中使用此代码:

@using (Html.BeginForm("Guestlogin", "Home", FormMethod.Post))
        {
            for (int i =0; i <1; i++)

在此之前添加以下代码:

   @{ Html.EnableClientValidation(); }
   @using (Html.BeginForm("Guestlogin", "Home", FormMethod.Post))
        {
            for (int i =0; i <1; i++)