MVC 3 razor TextBoxFor 与 ViewBag 项目抛出错误?
尝试使用我从 ViewBag 收到的数据在网页上打印出几种不同的表格。
第一个语句有效,但第二个语句无效:
@Html.EditorForModel(ViewBag.PI as PItem)
@Html.TextBoxFor(x => (ViewBag.PI as PItem).Text)
我还尝试了以下操作(相同的错误消息):
@Html.TextBoxFor(x => ViewBag.PI.Text)
第一个语句为 PItem 创建模型,第二个语句在我尝试为 PItem 内的文本项创建文本框时抛出错误。是否可以使用帮助程序的文本框打印 ViewBag 中的数据而不是模型中的数据?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
TextBoxFor
旨在与强类型视图和视图模型一起使用。因此,剪切ViewData/ViewBag
c..p 并正确使用这些帮助器:如果需要循环,请使用 EditorTemplates:
并在相应的编辑器模板内:
不仅现在我们拥有 IntelliSense 和强类型,而且除此之外,该代码还可以工作。
结论和我的 2 美分:不要在 ASP.NET MVC 中使用 ViewBag/ViewData 并感到高兴。
TextBoxFor
is intended to be used with strongly typed views and view models. So cut theViewData/ViewBag
c..p and use those helpers correctly:If you need to loop, use EditorTemplates:
and inside the corresponding editor template:
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.