Pass a ViewBag instance to a HiddenFor field in Razor

crowsfeet picture crowsfeet · Dec 13, 2014 · Viewed 23.9k times · Source

Using ASP.NET MVC and Razor, I'm trying to pass a ViewBag item from the controller to a HiddenFor field (using Razor). I get the following message: Extension methods cannot by dynamically dispatched.

  @Html.HiddenFor(m=>m.PortfolioId, ViewBag.PortfolioId);

Answer

Prakash picture Prakash · Dec 13, 2014

You are getting this error because ViewBag is dynamic type. You can use ViewModel instead of ViewBag to solve this problem.

Alternatively you can use following or plain html as suggested by iceburg:

@Html.Hidden("id", (string)ViewBag.PortfolioId)