2012-02-16 63 views
3

我有一個看起來像這兩MVC模式:MVC模型類不會填充到後

public class OtherModel 
{ 
    [Required] 
    [Display(Name = "Another ID")] 
    public int id{ get; set; } 
} 

public class MyModel 
{ 
    [Required] 
    [Display(Name = "ID")] 
    public int id { get; set; } 


    public PlayerModel otherModel = new OtherModel(); 
} 

我的控制有一個[HttpPost]行動稱爲使用看起來像這樣:

[HttpPost] 
public ActionResult Use(MyModel myModel) 
{ 
    /// myModel.otherModel.id is 0 here!! 
} 

這行動需要一個MyModel。當我的表單發佈時,otherModel變量包含一個0作爲id值。現在,包含該表單的視圖將傳遞給MyModel,並實際在頁面上顯示otherModel.id。問題是後處理不是 正確地將表單數據編組到另一個模型對象,我不知道爲什麼。

另一個注意事項:當我檢查這篇文章的表單數據標題時,我清楚地看到otherModel.id與我期望的值。

爲什麼這個數據在我的otherModel對象中沒有正確顯示?

謝謝您提前!

+1

你可以發佈進入控制器的表單頭嗎? – Jesse 2012-02-16 14:54:16

+0

它也讓我想知道你是否設置了ID和另一個ID? – cpoDesign 2012-02-16 15:05:18

+0

其他模型真的是公衆會員而不是物業? – 2012-02-16 15:05:39

回答

1

您是否在Global.asax.cs中註冊了聯編程序?

public static void RegisterBinders(ModelBinderDictionary binders) 
{ 
    binders.Add(typeof(MyModel), new MyModelBinder()); 
    // other binders 
} 

這就是所謂的的Application_Start如下所示:

protected void Application_Start() 
{ 
    RegisterBinders(ModelBinders.Binders); 
} 

PS:我假設你使用的是自定義模型粘合劑。如果您使用自動綁定,請參閱您是否尊重命名約定。

+1

他從來沒有提到他爲自己的模型製作了模型綁定器,那爲什麼會這樣呢? – Falle1234 2012-02-16 15:28:05

+0

你說得對。這是我的假設,但自定義綁定消除了上面描述的這種麻煩。 – 2012-02-16 15:43:28

0

而不是初始化otherModel並在行PlayerModel otherModel = new OtherModel();處使用新對象,請使用屬性public PlayerModel otherModel { get; set; }otherModel需要模型聯編程序的屬性設置器來正確地分配值。這可能會要求您還要更改在顯示視圖時填充otherModel屬性的方式 - 構建一個對象並在顯示控制器方法或某種其他用於保存模型的函數中顯式指定該對象。

0

我有一個幾乎相同的問題。對於我來說,正如馬特所說的那樣,爲了讓內部對象成爲一個具有所需訪問器的屬性。

public class OuterModel 
{ 
    public OuterModel() 
    { 
     AuxData= new InnerModel(); 
    } 
    public InnerModel AuxData{ get; set; } 
} 

public class InnerModel 
{ 
    Int Id {get; set;} 
}