ASP.NET MVC 3 ListBox validation

2019-06-06 09:40发布

问题:

I'm currently experiencing a weird issue with ASP.NET MVC 3 ListBox validation, as stated in the title. Basically, I have a List in my viewmodel, which I bind to a ListBox with multiple selection enabled.

The List is given an attribute [Required]. When I submit the form with single value selected, it passes validation with no hiccups. However, with more than one, validation would fail.

Any thoughts?

回答1:

Weird, I am unable to reproduce your issue.

Model:

public class MyViewModel
{
    [Required(ErrorMessage = "Please select at least one item")]
    public string[] SelectedItems { get; set; }

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

Controller:

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

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

View:

@model MyViewModel

@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectedItems, Model.Items)
    @Html.ValidationMessageFor(x => x.SelectedItems)
    <button type="submit">OK</button>
}

If you don't select any item in the list the validation error message is shown as expected. If you select one or more items the validation passes and no error message is displayed.