I\'m currently using the ModelStateDictionary in asp.net mvc to hold validation errors and pass then back to the user. Being able to check if the whole model is valid with Model
I used the solution from Simon Farrow as a starting point to make the warnings work with Kendo's datasource. By default you can return and show Data
OR Errors
but I wanted to return and show Data
AND Warnings
. So I've wrapped Kendo's DataSourceResult
and added another extension method which returns the collected warnings.
// The wrapper
public class DataSourceResultWithWarnings: DataSourceResult
{
public object Warnings { get; }
public DataSourceResultWithWarnings(DataSourceResult dataSourceResult, IDictionary>> warnings)
{
this.AggregateResults = dataSourceResult.AggregateResults;
this.Data = dataSourceResult.Data;
this.Errors = dataSourceResult.Errors;
this.Total = dataSourceResult.Total;
Warnings = warnings;
}
}
// The extension method
public static IDictionary>> GetWarnings(this ModelStateDictionary msd)
{
var result = new Dictionary>>();
for (var i = 0; i < msd.Values.Count; i++)
{
var wms = msd.Values.ElementAt(i) as WarningModelState;
if (wms != null)
{
if (!result.ContainsKey(msd.Keys.ElementAt(i)))
{
result.Add(msd.Keys.ElementAt(i), new Dictionary>() { { "warnings", new List() } });
}
result[msd.Keys.ElementAt(i)]["warnings"].AddRange((from rec in wms.Warnings select rec.ErrorMessage));
}
}
return result;
}
// How to use it in the controller action
var result = new DataSourceResultWithWarnings(files.Values.ToDataSourceResult(request, ModelState), ModelState.GetWarnings());
return Json(result, JsonRequestBehavior.AllowGet);