Say I have a Dictionary
and I want to update an object with the values from the dictionary, just like model binding in MVC... how would yo
You could use the DefaultModelBinder to achieve this but you will need to reference the System.Web.Mvc assembly to your project. Here's an example:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
public class MyViewModel
{
[Required]
public string Foo { get; set; }
public Bar Bar { get; set; }
}
public class Bar
{
public int Id { get; set; }
}
public class Program
{
static void Main()
{
var dic = new Dictionary
{
{ "foo", "" }, // explicitly left empty to show a model error
{ "bar.id", "123" },
};
var modelState = new ModelStateDictionary();
var model = new MyViewModel();
if (!TryUpdateModel(model, dic, modelState))
{
var errors = modelState
.Where(x => x.Value.Errors.Count > 0)
.SelectMany(x => x.Value.Errors)
.Select(x => x.ErrorMessage);
Console.WriteLine(string.Join(Environment.NewLine, errors));
}
else
{
Console.WriteLine("the model was successfully bound");
// you could use the model instance here, all the properties
// will be bound from the dictionary
}
}
public static bool TryUpdateModel(TModel model, IDictionary values, ModelStateDictionary modelState) where TModel : class
{
var binder = new DefaultModelBinder();
var vp = new DictionaryValueProvider