2014-11-24 2 views
0

웹 페이지의 MVC에서와 같이 객체에 오는 요청 값을 바인딩하는 방법이 있는지 궁금합니다.Asp.net 면도기 웹 페이지 값을 객체에 바인딩

웹 페이지는 mvc보다 작은 웹 사이트를 개발하는 간단한 방법입니다. 그래서 면도기 웹 페이지를 사용하여 지금 웹 사이트를 개발하고 싶습니다.

오랫동안 MVC를 사용했고 규칙에 따라 자동 모델 바인딩이있었습니다. 그리고 어떤 액션에서도 TryUpdateModel() 메서드를 사용하여 복잡한 객체에 요청 값을 바인딩하여 멋진 작업을 수행 할 수 있습니다.

페이지에서 볼 수있는 ModelBinders.Binders.DefaultBinder.BindModel() 방법이 있지만 두 개의 긴 매개 변수가 필요합니다. 내가 궁금

C#을 객체 : 도움을

들으에 바인드 요청 매개 변수에 대한 간단한 빠른 방법이있다.

답변

2

웹 페이지 프레임 워크에는 모델 바인딩이 없습니다. 이 프레임 워크는 초보자 개발자를 염두에두고 개발되었으며 프로젝트 팀원이 당시에 보았던 의견을 토대로 대상 독자가 데이터 (비즈니스 개체)에 강력하게 형식화 된 컨테이너를 이해하거나 사용하지 않을 것이라고 생각했습니다.

내가 작업 한 프로젝트에 이와 같은 것이 필요했기 때문에 매우 간단한 모델 바인더를 만들었습니다. 단순한 유형 만 처리하고 모든 종류의 코드 작성기를 거치지 않은 대략적인 코드이지만 내 용도로 사용됩니다. 당신은 더 강력한 무언가의 기초를 위해 그것을 사용할 수 있습니다

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
using System.Web; 

public static class RequestBinder 
{ 
    /// <summary> 
    /// Generates entity instances from Request values 
    /// </summary> 
    /// <typeparam name="TEntity">The Type to be generated</typeparam> 
    /// <param name="request"></param> 
    /// <returns>TEntity</returns> 
    public static TEntity Bind<TEntity>(this HttpRequestBase request) where TEntity : class, new() 
    { 
     var entity = (TEntity)Activator.CreateInstance(typeof(TEntity)); 
     var properties = typeof(TEntity).GetProperties(); 
     foreach (var property in properties) 
     { 
      object safeValue; 
      Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; 
      try 
      { 
       if (t == typeof(String)) 
       { 
        safeValue = string.IsNullOrEmpty(request[property.Name]) ? null : request[property.Name]; 
       } 
       else if (t.IsEnum) 
       { 
        safeValue = (request[property.Name] == null) ? null : Enum.Parse(t, request[property.Name]); 
       } 
       else 
       { 
        Type tColl = typeof(ICollection<>); 
        if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) || t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) 
        { 
         continue; 
        } 
        safeValue = (request[property.Name] == null) ? null : Convert.ChangeType(request[property.Name], t); 
       } 
       property.SetValue(entity, safeValue, null); 
      } 
      catch (Exception) 
      { 

      } 
     } 
     return entity; 
    } 

    /// <summary> 
    /// Populates an existing entity's properties from the Request.Form collection 
    /// </summary> 
    /// <typeparam name="TEntity"></typeparam> 
    /// <param name="request"></param> 
    /// <param name="entity"></param> 
    /// <returns></returns> 
    public static TEntity Bind<TEntity>(this HttpRequestBase request, TEntity entity) where TEntity : class, new() 
    { 
     foreach (string item in request.Form) 
     { 
      var property = entity.GetType().GetProperty(item); 
      if (property != null) 
      { 
       object safeValue; 
       Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType; 
       try 
       { 
        if (t == typeof(String)) 
        { 
         safeValue = string.IsNullOrEmpty(request[property.Name]) ? null : request[property.Name]; 
        } 
        else if (t.IsEnum) 
        { 
         safeValue = (request[property.Name] == null) ? null : Enum.Parse(t, request[property.Name]); 
        } 
        else 
        { 
         Type tColl = typeof(ICollection<>); 
         if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) || t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) 
         { 
          continue; 
         } 
         safeValue = (request[property.Name] == null) ? null : Convert.ChangeType(request[property.Name], t); 
        } 
        property.SetValue(entity, safeValue, null); 
       } 
       catch (Exception) 
       { 

       } 
      } 
     } 
     return entity; 
    } 
} 

당신은 다음과 같이 사용합니다 :

var person = Request.Bind<Person>(); 

그것은 웹 페이지는 ASP.NET vNext에 통합되는 방법을 순간에 불분명하다. ASP.NET 팀은 Web Pages, MVC 및 Web API에서 중복을 제거하는 방법에 대해 이야기했습니다. 따라서 Model Binding을 포함한 웹 페이지가 만들어지기를 바랍니다.