2012-11-22 22 views
1

我有一個自定義對象的視圖模型。在最初的get,我填充Foo並使用Foo的幾個屬性。如何在MVC中包含所有自定義對象屬性4 HttpPost

在帖子上,我發現視圖模型上的Foo爲null。

我可以添加到我的視圖@Html.HiddenFor(x => x.Foo.Id)這可以確保Foo至少填充了一個ID,但是然後我可能需要爲所有屬性添加類似的代碼。

有沒有辦法發回完整的對象?

public class RequestModel 
    { 
     public Foo Foo{ get; set; } 

     [Required] 
     [Display(Name = "Comment")] 
     public string Comment { get; set; } 
    } 

控制器

public ActionResult Index(int? id) 
{ 
    //Populate Foo here using EF and add it to the model 
    var model = new RequestModel { Foo = foo };  
    return View(model); 
} 



[HttpPost] 
public ActionResult Index(int? id, RequestModel model) 
{ 
    return View(model); 
} 

查看

@Html.DisplayTextFor(m=>m.Application.Name) 

+0

你可以從視圖和控制器添加代碼嗎? – heads5150

+0

我已更新該問題。我想我的問題是虛擬機是否應該公開EF對象,或者控制器是否應該將簡單值映射到視圖上。 – Kye

+0

爲什麼你想發送所有'Foo'屬性回到動作? – Jan

回答

1

添加視圖模型與您希望您的解決方案的性能。把你的驗證等,並使用它來移動你的頁面和控制器之間的數據,然後將屬性映射到您的EF對象。

相關問題