是模型绑定可能不MVC? [英] Is model binding possible without mvc?

查看:111
本文介绍了是模型绑定可能不MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个词典<字符串,字符串> ,我想更新从词典中值的对象,就像模型MVC结合...如何你会做,如果没有MVC?

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?

推荐答案

您可以使用DefaultModelBinder来实现这一点,但你需要将System.Web.Mvc集引用到您的项目。这里有一个例子:

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

这篇关于是模型绑定可能不MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆