从 ASP.NET MVC 视图中获取对象列表的最佳实践
我有一个像 Now 这样的类
public class Questions
{
public long ID { get; set; }
public string questionText { get; set; }
public int questionType { get; set; }
}
,当在视图中创建并提交各种问题时,控制器的操作代码应该是什么,我应该如何设计我的视图,以便我可以直接获取所有属性设置的问题列表?
提前致谢。
I have one class like
public class Questions
{
public long ID { get; set; }
public string questionText { get; set; }
public int questionType { get; set; }
}
Now when various questions are created in the view and submitted, what should be the controller's action code and how should I design my view so that I can get the list of questions with all the properties set directly?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
模型绑定到
IList
我已经写过关于模型绑定到
IList
的文章。我认为这正是您想要解决的问题。我的博客上还有更多帖子可能对您有很大帮助,特别是因为您没有说明您是否有 HTML 形式的问题或由某些通用问题形式构建的 Javascript 对象。反正。这两篇文章将帮助您解决这两个问题:IList
通过了解 Asp.net MVC 模型绑定,您将能够轻松地将客户端数据(表单或对象)绑定到:
假设您要回发 HTML 表单
主要要求是为 HTML 字段建立索引名称正确,因为名称是那些被发布回服务器的名称。在您的情况下,您的字段应该是:
当您动态添加新对(以形成新问题)时,您必须确保:
如果您还提供删除某些问题的功能(在添加/编辑它们时),则必须在每次删除时重新索引项目。
模型验证(表单或正确准备的对象)
这样做的好处是,您可以将数据注释属性添加到应用程序模型类中,并自动验证您发布的对象,因此您不必自己执行此操作。
Model binding to
IList<T>
I've written about model binding to
IList<T>
. I think this is exactly the problem that you're trying to solve. And there are some more posts on my blog that may help you lots especially because you didn't say whether you're having an HTML form of questions or Javascript objects built by some generic question form. Anyway. These two posts will help you address both problems:IList<T>
By understanding Asp.net MVC model binding you will be able to easily bind your client-side data (forms or objects) to:
Suppose you're posting back an HTML form
The main requirement is that you index your HTML field names correctly, because names are those that get posted back to server. In your case your fields should be:
When you dynamically add new pairs (to form new questions) you have to make sure:
If you also provide the ability to remove certain questions (while adding/editing them), you will have to reindex items on each removal.
Model validation (forms or correctly prepared objects)
The great thing about doing it this way is that you can put data annotations attributes to your application model class and get your posted objects automatically validated, so you don't have to do this yourself.