无法强制列表< int>被要求 [英] Can't force List<int> to be required

查看:79
本文介绍了无法强制列表< int>被要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数据注释来添加验证到我的模型中的列表,不能为空。我已经尝试了一些自定义属性的几个实现,包括此处和< a href =https://stackoverflow.com/questions/5146732/viewmodel-validation-for-a-list> here 。

I'm trying to use Data Annotations to add validation to a List in my model that cannot be empty. I've tried several implementations of a custom attribute, including ones here and here.

我的观点:

<div class="form-group">
    @* Model has a list of ints, LocationIDs *@
    @Html.LabelFor(model => model.LocationIDs, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        <select class="select2 form-control" multiple id="LocationIDs" name="LocationIDs">
            @* Adds every possible option to select box *@
            @foreach (LocationModel loc in db.Locations)
            {
                <option value="@loc.ID">@loc.Name</option>
            }
        </select>
        @Html.ValidationMessageFor(model => model.LocationIDs, "", new { @class = "text-danger" })
    </div>
</div>

型号:

public class ClientModel
{
    public int ID { get; set; }
    [Required] // Does nothing
    public List<int> LocationIDs { get; set; }
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,LocationIDs")] ClientModel clientModel)
{
    if (ModelState.IsValid)
    {
        db.Clients.Add(clientModel);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(clientModel);
}

我尝试过的(功能完全相同)属性之一:

One of the (functionally identical) attributes I've tried:

[AttributeUsage(AttributeTargets.Property)]
public sealed class CannotBeEmptyAttribute : RequiredAttribute
{
    public override bool IsValid(object value)
    {
        var list = value as IEnumerable;
        return list != null && list.GetEnumerator().MoveNext();
    }
}

目前,检查空或空列表通过验证,即使没有选择。在这种情况下,包含第一个选项的长度为1的列表将被绑定。

Currently, checking for a null or empty list passes validation, even if nothing is chosen. In this case, a list of length one, containing the first option, is bound.

我已经确认控制器实际上是发送一个长度为1的列表。但是,我不知道如何改变这种行为。我仍然认为这可能是下面的块引用所描述的。

I've confirmed that the controller is actually sent a List of length one. I'm not sure how to change this behavior, however. I still think this may be what was described in the below block quote.

/ em> 我的问题可能会在此答案的编辑中描述,但我不确定如何解决。

I think my problem may be described in this answer's edit, but I'm not sure how to solve it.

以下摘录:


您还必须小心,在您的视图中绑定列表。
例如,如果您将列表绑定到如下视图:

You'll also have to be careful how you bind your list in your view. For example, if you bind a List to a view like this:



<input name="ListName[0]" type="text" />
<input name="ListName[1]" type="text" />
<input name="ListName[2]" type="text" />
<input name="ListName[3]" type="text" />
<input name="ListName[4]" type="text" /> 




MVC模型binder将始终将5个元素放在
列表,全部为String.Empty。如果这是您的View的工作原理,您的属性
将需要更复杂一些,例如使用Reflection来拉
通用类型参数,并将每个列表元素与
default(T )或某事。

The MVC model binder will always put 5 elements in your list, all String.Empty. If this is how your View works, your attribute would need to get a bit more complex, such as using Reflection to pull the generic type parameter and comparing each list element with default(T) or something.


推荐答案

我可以获得零选择的唯一方法来实际绑定因为 null 是通过使用 Html.ListBoxFor (我最初无法弄清楚–它应该已经完成​​了这样从一开始):

The only way I could get a zero-selection to actually bind as null was by using Html.ListBoxFor (which I couldn't figure out initially – it should have been done this way from the start):

@Html.ListBoxFor(model => model.SelectedLocations, Model.AllLocations, new { @class = "select2 form-control" })

我没有得到客户端验证工作,但我会把这个作为另一个问题。

I haven't gotten client-side validation to work, but I'll post that as another question.

这篇关于无法强制列表&lt; int&gt;被要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆