列表中的MVC 3不显眼的审定 [英] MVC 3 Unobtrusive validation of a list

查看:197
本文介绍了列表中的MVC 3不显眼的审定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个服务器端的属性级的验证属性。但是,而不是把它应用到单个字段我已经把它应用到一个列表。这让我来验证模型的全过程。

I have created a server-side property level validation attribute. But instead of applying it to an individual field I've applied it to a List. This allows me to validate the model as a whole.

我现在需要知道如何转换这种使用内置到MVC 3不显眼的客户端验证工作。

I now need to know how to convert this to work using the unobtrusive client-side validation built into MVC 3.

我目前的code是下面来说明我的问题...

My current code is below to illustrate my issue...

场景

的基本情况是能力总计所有的每一行的数量值由GroupNo场分组列表。如果任一组的总和超过10接着应显示一个错误。

The basic scenario was the ability total up all the Quantity values for every row in a List grouped by the GroupNo field. If the sum of any of the groups was more than 10 then an error should be displayed.

我是好心给了previous后一个答案使用针对列表验证属性,使这项工作的服务器端...

I was kindly given an answer in a previous post to make this work server-side using a validation attribute against a List...

模型:

public class ItemDetails
{
    public int SerialNo { get; set; }
    public string Description { get; set; }
    public int GroupNo { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
}

public class MyViewModel
{
    [EnsureMaxGroupItems(10, ErrorMessage = "You cannot have more than 10 items in each group")]
    public IList<ItemDetails> Items { get; set; }
}

和验证属性本身:

[AttributeUsage(AttributeTargets.Property)]
public class EnsureMaxGroupItemsAttribute : ValidationAttribute
{
    public int MaxItems { get; private set; }

    public EnsureMaxGroupItemsAttribute(int maxItems)
    {
        MaxItems = maxItems;
    }

    public override bool IsValid(object value)
    {
        var items = value as IEnumerable<ItemDetails>;
        if (items == null)
        {
            return true;
        }

        return items
            .GroupBy(x => x.GroupNo)
            .Select(g => g.Sum(x => x.Quantity))
            .All(quantity => quantity <= MaxItems);
    }
}

和最后你的控制器动作将与视图模型工作:

and finally your controller actions will work with the view model:

public ActionResult ListItems()
{
    var model = new MyViewModel
    {
        Items = ItemsRepository.GetItems()
    };
    return View(model);
}

[HttpPost]
public ActionResult ListItems(MyViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    ...
}

和下一个相应的强类型的视图:

and next the corresponding strongly typed view:

@model MyViewModel
@Html.ValidationSummary()
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.Items)
    <button type="submit">Go go go</button>
}

和最后的一点是,会自动输出呈现项集合中的每个元素,让你甚至都不需要编写for循环(〜/查看/共享/ EditorTemplates相应的编辑器模板/ItemDetails.cshtml

and the last bit is the corresponding editor template that will automatically be rendered for each element of the Items collection so that you don't even need to write for loops (~/Views/Shared/EditorTemplates/ItemDetails.cshtml):

@model ItemDetails
@Html.HiddenFor(x => x.SerialNo)
@Html.LabelFor(x => x.Description)
@Html.HiddenFor(x => x.GroupNo)
@Html.LabelFor(x => x.Price)
@Html.TextBoxFor(x => x.Quantity)

客户端不引人注目的验证可能吗?

我想这一切用不显眼的MVC验证验证。但我无法弄清楚如何悄悄地验证EnsureMaxGroupItemsAttribute属性对列表作为一个整体。

I would like it all to validate using unobtrusive MVC validation. But I cannot figure out how to unobtrusively validate the EnsureMaxGroupItemsAttribute attribute against the list as a whole.

我在这种方式实现IClientValidatable:

I've implemented IClientValidatable in this way:

    Public Function GetClientValidationRules(metadata As System.Web.Mvc.ModelMetadata, context As System.Web.Mvc.ControllerContext) As System.Collections.Generic.IEnumerable(Of System.Web.Mvc.ModelClientValidationRule) Implements System.Web.Mvc.IClientValidatable.GetClientValidationRules

        Dim result = New List(Of ModelClientValidationRule)

        Dim rule = New ModelClientValidationRule() With { _
            .ErrorMessage = "You cannot have more than 10 items in each group", _
            .ValidationType = "itemscheck"}

        result.Add(rule)

        Return result

    End Function

注:VB和C#的搭配只是因为previous问题,我问在C#中得到了回答。该项目是在VB,但我不介意在C#中的答案。

Note: the mix of VB and C# is only because the previous question I asked was answered in C#. The project is in VB but I don't mind an answer in C#.

我创建了适配器在我的JS文件:

I've created the adaptor in my JS file:

jQuery.validator.unobtrusive.adapters.addBool("itemscheck"); 

......然后......

... and ...

jQuery.validator.addMethod("itemscheck", function (value, element, params) {
    // The check has been omitted for the sake of saving space.  
    // However this method never gets called
    return false;
});

有没有办法挂钩这份长达悄悄地工作?

Is there a way to hook this up to work unobtrusively?

推荐答案

这是因为您的自定义属性被放置在集合属性是不可能的,也没有HTML5 数据 - * 属性发出的。它是不是由不显眼的客户端验证框架支持的方案。你可以直接写一个自定义JQuery验证规则,如果你需要客户端验证它处理这种情况。

This is not possible because your custom attribute is placed in the collection property and there are no HTML5 data-* attributes emitted at all. It is not a supported scenario by the unobtrusive client validation framework. You could write directly a custom jquery validate rule to handle this scenario if you need client validation for it.

这篇关于列表中的MVC 3不显眼的审定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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