2015-04-02 19 views
0

我需要你的幫助。通過asp.net中的ViewData.Model發送對象mvc

我試圖通過使用ViewData.Model

這是在控制器

public ActionResult Index() 
    { 
     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 
     dynamic stronglytyped = new { Amount = 10, Size = 20 }; 
     List<dynamic> ListOfAnynomous = new List<object> { new { amount = 10 } }; 


     ViewData.Model = ListOfAnynomous[0]; 
     return View(); 
    } 

索引方法對象形成視圖到所述控制器,這是視圖部分

 <div> 
      @Model.amount 

     </div> 

這是erro

'object' does not contain a definition for 'amount' 

請任何人都可以幫助我。

+0

請勿使用'object'和'dynamic'。創建視圖模型並將視圖模型傳遞給視圖。 – 2015-04-02 10:00:11

+0

@StephenMuecke謝謝,我得到了解決方案,但請你能解釋爲什麼編譯器沒有看到動態對象定義。 – Moh 2015-04-02 10:29:37

+0

@StephenMuecke我希望把你的評論作爲答案接受 – Moh 2015-04-02 10:39:53

回答

0

的異常被拋出,因爲你傳遞一個匿名對象。匿名類型是內部的,所以它們的屬性不能在其定義的程序集之外被看到。 This article給出了一個很好的解釋。

雖然你可以使用HTML輔助渲染性能,例如

@Html.DisplayFor("amount") 

,你也將失去IntelliSense和你的應用程序將是難以調試。

改爲使用視圖模型來表示要顯示/編輯的內容並將模型傳遞到視圖。

-1

您的代碼是錯誤的。 如果你想使用模式對象,你必須把它傳遞給視圖:

return View(ListOfAnynomous[0]); 

,你將能夠使用「模型」屬性後。 ViewData是另一個與模型屬性無關的容器。

到底你的方法是這樣的:

public ActionResult Index() 
    { 
     ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application."; 
     dynamic stronglytyped = new { Amount = 10, Size = 20 }; 
     List<dynamic> ListOfAnynomous = new List<object> { new { amount = 10 } }; 


     // ViewData.Model = ListOfAnynomous[0]; 
     return View(ListOfAnynomous[0]); 
    }