Reputation: 5592
Trying to print out several different forms on the webpage with the data that i have received from the ViewBag.
The first statement works but no the second:
@Html.EditorForModel(ViewBag.PI as PItem)
@Html.TextBoxFor(x => (ViewBag.PI as PItem).Text)
I also tried the following (same error message):
@Html.TextBoxFor(x => ViewBag.PI.Text)
The first one creates a model for the PItem and the second throws an error when i try to create a textbox for the Text item inside PItem. Is it possible to use the textboxfor helper to print out data from the ViewBag and not from the model?
Upvotes: 1
Views: 4717
Reputation: 1038720
TextBoxFor
is intended to be used with strongly typed views and view models. So cut the ViewData/ViewBag
c..p and use those helpers correctly:
@model MyViewModel
@Html.TextBoxFor(x => x.Text)
If you need to loop, use EditorTemplates:
@model IEnumerable<MyViewModel>
@Html.EditorForModel()
and inside the corresponding editor template:
@model MyViewModel
<div>@Html.TextBoxFor(x => x.Text)</div>
Not only that now we have IntelliSense and strong typing but in addition to this the code works.
Conclusion and my 2¢: don't use ViewBag/ViewData in ASP.NET MVC and be happy.
Upvotes: 5