MVC 3 razor TextBoxFor with ViewBag item throws an error?
-
15-11-2019 - |
Question
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?
Solution
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.