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

前端 未结 5 1283
盖世英雄少女心
盖世英雄少女心 2020-12-15 12:18

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 se

5条回答
  •  忘掉有多难
    2020-12-15 12:50

    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 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";
    }
    
    
    
    @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)
        
    }
    

    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.

提交回复
热议问题