2012-06-09 25 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; } 
} 

現在考慮下面的ASP.NET MVC 3行動接受在各自的格式(基於accept頭)JSON或XML請求和返回模型。

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」,則信息將被正確序列化。

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

如預期的那樣,默認綁定器在將傳入值映射到模型時使用屬性名稱。我看了一下BindAttribute,但是它的屬性不支持。

如何告訴ASP.NET MVC 3屬性IsReallyImportant應該在傳入請求中綁定爲「重要」?

我有太多的模型來編寫每個自定義綁定。請注意,我不使用ASP.NET Web API。

回答

0

您只能執行一個自定義ModelBinder,它將查找JSonProperty和XMLElement屬性以映射正確的屬性。這樣你可以在任何地方使用它,你不必爲每個模型開發一個模型綁定器。不幸的是,除自定義模型綁定器之外,沒有其他選項可以修改屬性綁定。

+0

謝謝你做到了。 – bloudraak

相關問題