问题
Say I have a Dictionary<string, string>
and I want to update an object with the values from the dictionary, just like model binding in MVC... how would you do that without MVC?
回答1:
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<string, object>
{
{ "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>(TModel model, IDictionary<string, object> values, ModelStateDictionary modelState) where TModel : class
{
var binder = new DefaultModelBinder();
var vp = new DictionaryValueProvider<object>(values, CultureInfo.CurrentCulture);
var bindingContext = new ModelBindingContext
{
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(TModel)),
ModelState = modelState,
PropertyFilter = propertyName => true,
ValueProvider = vp
};
var ctx = new ControllerContext();
binder.BindModel(ctx, bindingContext);
return modelState.IsValid;
}
}
回答2:
You can do that, but you would still need to reference System.Web.Mvc, obviously. It is more or less a matter of constructing a ModelBinder, perhaps the DefaultModelBinder
, then call it with the appropiate arguments - but those arguments, unfortunately, is very closely bound to the web scenario.
Depending on what you exactly want, it might make more sense to roll your own simple reflection based solution.
来源:https://stackoverflow.com/questions/12788948/is-model-binding-possible-without-mvc