问题描述:

I have a peculiar scenario in which i need to validate an object that isn't my model and get all the ValidationResult objects from it.

So my controller has something like this in it ...

public virtual ActionResult(MyObject postData)

{

ICollection someCollection = DoSomething(postData);

foreach(Thing t in someCollection)

{

// validate t and get any ValidationResult objects

// put the validation results in the object property.

// this call isn't real by the way

t.ValidationResults = t.Validate();

}

...

}

Its not my model i'm validating but based on the postdata i'm given i need to validate the collection and where the validation fails I plan to render the failed objects in the collection.

any ideas how I can the ValidationResult objects I want?

网友答案:

This article on manual validation with data annotations might give you what you need.

网友答案:

You could store the ValidationResults in the ViewBag and then render them from there:

var list = new List<ValidationResult>();
foreach (Thing t in someCollection)
{
    t.ValidationResults = t.Validate();
    list.AddRange(t.ValidationResults);
}
ViewBag.ValidationResults = list;

now, a lot of that code makes a lot of assumptions because you aren't providing a lot of information. But either which way, get those results into an overall list and set them in the ViewBag. You can then leverage the ViewBag in the view:

@foreach (ValidationResult r in ViewBag.ValidationResults)
{
   <!-- render some HTML here  with the r variable -->
}
相关阅读:
Top