2012-06-09 4 views
2

XmlSerializerJSON.net을 사용하여 각 형식으로 개체를 직렬화하는 다음 모델을 고려하십시오.ASP.NET MVC 3을 사용하여 필드의 값을 다른 이름의 속성에 바인딩하는 방법은 무엇입니까?

[XmlRoot("my_model")] 
[JsonObject("my_model")] 
public class MyModel { 

    [JsonProperty("property1")] 
    [XmlElement("property1")] 
    public string Property1 { get; set; } 

    [JsonProperty("important")] 
    [XmlElement("important")] 
    public string IsReallyImportant { get; set; } 
} 

지금 (수락 헤더에 따라) 각각의 형식으로 JSON 또는 XML 요청 및 반환 모델을 받아 다음과 같은 ASP.NET MVC 3 조치를 고려한다.

public class MyController { 
    public ActionResult Post(MyModel model) { 

     // process model 

     string acceptType = Request.AcceptTypes[0]; 
     int index = acceptType.IndexOf(';'); 
     if (index > 0) 
     { 
      acceptType = item.Substring(0, index); 
     } 

     switch(acceptType) { 
      case "application/xml": 
      case "text/xml": 
       return new XmlResult(model); 

      case "application/json": 
       return new JsonNetResult(model); 

      default: 
       return View(); 
     } 
    } 
} 

사용자 정의 ValueProviderFactory 구현은 JSON 및 XML 입력을 위해 존재한다. 그대로 입력이 MyModel에 매핑 될 때 IsReallyImportant이 무시됩니다. 그러나 IsReallyImportant의 특성을 "isreallyimportant"를 사용하도록 정의하면 정보가 올바르게 serialize됩니다.

[JsonProperty("isreallyimportant")] 
[XmlElement("isreallyimportant")] 
public string IsReallyImportant { get; set; } 

예상대로 기본 바인더는 들어오는 값을 모델에 매핑 할 때 속성 이름을 사용합니다. 나는 BindAttribute을 보았지만 속성에는 지원되지 않습니다.

들어오는 요청에서 IsReallyImportant 속성이 "중요"로 바인딩되어야한다고 ASP.NET MVC 3에 알리는 방법은 무엇입니까?

각 모델에 맞춤식 바인더를 쓸 수있는 모델이 너무 많습니다. ASP.NET 웹 API는 사용하지 않습니다.

답변

0

올바른 특성을 매핑하기 위해 JSonProperty 및 XMLElement 특성을 찾을 수있는 하나의 사용자 정의 ModelBinder 만 수행 할 수 있습니다. 이렇게하면 어디서나 사용할 수 있으므로 각 모델에 모델 바인더를 개발할 필요가 없습니다. 불행하게도, 사용자 정의 모델 결합 자보다 특성 바인딩을 수정할 수있는 다른 옵션은 없습니다.

+0

트릭을 해 주셔서 감사합니다. – bloudraak

관련 문제