2015-04-02 28 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]); 
    }