Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a ViewBag instance to a HiddenFor field in Razor

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);
like image 992
crowsfeet Avatar asked Dec 13 '14 08:12

crowsfeet


3 Answers

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)
like image 200
Prakash Avatar answered Oct 07 '22 23:10

Prakash


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" />
like image 24
iceburg Avatar answered Oct 07 '22 21:10

iceburg


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

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

like image 35
Atakan Günay Avatar answered Oct 07 '22 22:10

Atakan Günay