ASP.NET MVC 3 列表框验证

发布于 2024-12-17 11:29:14 字数 170 浏览 2 评论 0原文

我目前在 ASP.NET MVC 3 ListBox 验证中遇到一个奇怪的问题,如标题中所述。基本上,我的视图模型中有一个列表,我将其绑定到启用了多重选择的列表框。

该列表被赋予一个属性[必需]。当我提交选择了单个值的表单时,它顺利通过了验证。但是,如果超过一个,验证就会失败。

有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淡淡離愁欲言轉身 2024-12-24 11:29:15

奇怪的是,我无法重现你的问题。

模型:

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

控制器:

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

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

视图:

@model MyViewModel

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

如果您未选择列表中的任何项目,则会按预期显示验证错误消息。如果您选择一项或多项,验证将通过并且不会显示错误消息。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文