为什么我的 EditorTemplate 没有在 [HttpPost] 上绑定列表,但在 [HttpGet] 上呈现得很好?
我已将代码上传到pastebin,这是链接:
当我提交时一个表单,我使用的列表未绑定到我的 ViewModel。
但是当我将 ViewModel 发送到视图时,它使用 EditorFor 渲染得很好。我读过,在使用 EditorTemplates 时,应该适当地命名列表,以便它们在回发时自动绑定到 ViewModel。
HTML 输出可以在此处看到:
请注意,ViewModel 派生自 ShowQuestionViewModel,其中包含一些字符串。这些绳子完美地绑在一起。
这是我一直在遵循的教程:
http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3
在本教程中,MVC 框架知道如何在 ViewModel 内部绑定列表。
以下是一些调试器输出:
控制器采用 ShowQuestionViewModel 作为参数:
http://imageshack.us/photo/my-images/803/debug.jpg
控制器采用 FormCollection 作为参数:
http ://imageshack.us/photo/my-images /542/formcollection.png
以 List 和 FormCollection 作为参数的不同控制器:
http: //imageshack.us/photo/my-images/685/listtest.png
不要放弃我 伙计们!!
谢谢!
解决方案
我自己找到了这个解决方案。我忘记使用 ShowMatrixQuestionViewModel 中的行和列列表的属性。另外,如果没有 TryUpdateModel(),ActionController 就不会绑定,所以要感谢 @Adam Tuliper 以及其他人。
I have uploaded my code to pastebin, this is the link:
When i submit a form, the Lists that i use are not bound to my ViewModel.
But when i send the ViewModel to the view, it renders fine using EditorFor. I have read that when using EditorTemplates, it is supposed to name the List appropriately so that they are bound to the ViewModel automatically upon postback.
The HTML output can be seen here:
Notice that the ViewModel derives from ShowQuestionViewModel, which contains some strings. These strings get bound perfectly.
This is the tutorial i have been following:
http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3
In the tutorial, the MVC framework knows how to bind lists inside of a ViewModel.
Here are some debugger outputs:
Controller takes ShowQuestionViewModel as parameter:
http://imageshack.us/photo/my-images/803/debug.jpg
Controller takes FormCollection as parameter:
http://imageshack.us/photo/my-images/542/formcollection.png
Different Controller that takes a List and FormCollection as parameter:
http://imageshack.us/photo/my-images/685/listtest.png
Dont give up on me guys!!
Thanks!
Solution
I have found this solutin myself. I forgot to use Properties for the rows and columns list in the ShowMatrixQuestionViewModel. Also, the ActionController wont bind without TryUpdateModel() so thanks to @Adam Tuliper as well as the rest.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
既然您提到了列表,您确定您的模型在回发后包含所有预期的项目吗?另请记住,如果您在发布后显示数据而不是重定向,则 HTML 帮助程序也会使用 modelstate 来绑定数据。
Since you mentioned lists are you sure your model Upon postback contains all of the expected items? Also remembe the HTML helpers will use modelstate to bind data from as well if you are showing data after a post and not redirecting.