crowsfeet
crowsfeet

Reputation: 203

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

Upvotes: 6

Views: 26360

Answers (3)

Atakan Günay
Atakan Günay

Reputation: 27

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

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

Upvotes: 2

Prakash
Prakash

Reputation: 809

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)

Upvotes: 25

iceburg
iceburg

Reputation: 1768

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" />

Upvotes: 2

Related Questions