mercredi 11 novembre 2015

ViewModel validation for a List and display the error message

i need to do a validation by ensuring the list must have atleast one item is selected. I populate the checkbox with my list, below is the code

@for (var i = 0; i < Model.ProductList.Count(); i++)
    var product = Model.ProductList[i];
    @Html.HiddenFor(model => model.ProductList[i].ProductId)
    @Html.CheckBoxFor(model => model.ProductList[i].Selected)
    @Html.LabelFor(model => model.ProductList[i].ProductName, product.ProductName, new { style="margin-right:10px" })
<span class="text-danger">@Html.ValidationMessageFor(model => model.ProductList)</span>

Here is my custom validation rule

public class MustHaveOneProductSelected : ValidationAttribute
    public override bool IsValid(object value)
        var products = value as List<MediaContentTypeProductItem>;
        int selected_count = products.Where(x => x.Selected).Count();
        if (selected_count <= 0)
            return false;
            return true;

Apply validation in a list

[MustHaveOneProductSelected(ErrorMessage = "Please select atleast one product.")]
public List<MediaContentTypeProductItem> ProductList { get; set; }

The MustHaveOneProductSelected is validate correctly by returning true and false. Just it wont display the error message. Am i missed out anything?

Aucun commentaire:

Enregistrer un commentaire