6

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);
crowsfeet
  • 203
  • 1
  • 4
  • 16
  • Does you model have a property `PortfolioId`? I assume you do not understand `@Html.HiddenFor()` - the second parameter is for rendering the html attributes –  Dec 13 '14 at 08:39

3 Answers3

24

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)
Prakash
  • 789
  • 6
  • 9
2

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" />
iceburg
  • 1,768
  • 3
  • 17
  • 25
2

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

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

SCouto
  • 7,808
  • 5
  • 32
  • 49
Atakan Günay
  • 27
  • 1
  • 3