Is model binding possible without mvc?

后端 未结 2 1610
走了就别回头了
走了就别回头了 2021-01-16 09:43

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

2条回答
  •  温柔的废话
    2021-01-16 10:31

    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(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;
        }
    }
    
        

    提交回复
    热议问题