Pass a ViewBag instance to a HiddenFor field in Razor

26k Views Asked by At

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);
3

There are 3 best solutions below

0
On

I'm not sure how to do it with the helper but you can achieve the same markup useing plain html:

<input type="hidden" name="PortfolioId" id="PortfolioId" value="@ViewBag.PortfolioId" />
1
On

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)
1
On

@Html.HiddenFor(i =>i.PortfolioId, htmlAttributes: new { @Value = ViewBag.PortfolioId })

will solve your problem if your "PortfolioId" is really a property model.