2012-10-08 3 views
1

Dictionary<string, string>이 있는데 MVC의 모델 바인딩과 마찬가지로 사전의 값을 사용하여 개체를 업데이트하고 싶습니다. MVC가 없으면 어떻게할까요?mvc없이 모델 바인딩이 가능합니까?

+0

예. 더 구체적으로 말하십시오. 무엇을 성취하고 싶습니까? 프레임 워크를 사용하지 않고 사전을 객체에 매핑. 비 MVC 시나리오에서 System.Web.Mvc에있는 modelbinder를 다시 사용하십니까? 다른 것 ? – driis

+0

예 : System.Web.Mvc에있는 modelbinder를 non-mvc 시나리오에서 다시 사용하십시오. –

답변

4

이 작업을 수행하려면 DefaultModelBinder를 사용할 수 있지만 System.Web.Mvc 어셈블리를 프로젝트에 참조해야합니다. 예를 들면 다음과 같습니다.

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

이렇게 할 수는 있지만 여전히 System.Web.Mvc를 참조해야합니다. ModelBinder를 구성하는 것은 아마도 DefaultModelBinder 일 것입니다. 그런 다음 적절한 인수로 호출하십시오.하지만 이러한 인수는 유감스럽게도 웹 시나리오와 매우 밀접하게 관련되어 있습니다.

정확히 무엇을 원 하느냐에 따라 자신의 간단한 리플렉션 기반 솔루션을 롤하는 것이 더 합리적 일 수 있습니다.

관련 문제