send object through ViewData.Model in asp.net mvc

2020-05-03 13:32发布

问题:

I need your help.

I tried to pass object form the view to the controller using ViewData.Model

this is the index method in the controller

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();
    }

and this is the view part

        <div>
             @Model.amount 

        </div>

this is the erro

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

please could anyone help me.

回答1:

The exception is thrown because you passing an anonymous object. Anonymous types are internal, so their properties can't be seen outside their defining assembly. This article gives a good explanation.

While you can use the html helpers to render the properties, for example

@Html.DisplayFor("amount")

you will also lose intellisense and you app will be difficult to debug.

Instead use a view model to represent what you want to display/edit and pass the model to the view.



回答2:

Your code is wrong. If you want to use the model object you have pass it to the view:

return View(ListOfAnynomous[0]);

After you will be able to use the "Model" property. ViewData is another container not related to the model property.

In the end your method will look like this:

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]);
    }