使用 ASP.NET MVC 将数据传递和返回到简单的网格表单
我有一个带有简单表格和高级搜索表单的页面。我将 List
传递给模型:
View(List<Customers>);
那么将数据传递和返回到搜索表单的最佳方式是什么?我想使用验证或其他东西,但我认为通过 ViewData 传递数据不是一个好主意。有什么建议吗?
I have page with a simple table and advanced search form. I pass List<Customers>
to the model:
View(List<Customers>);
So what is best way to pass and return data to the search form? I want to use validation or something but I think passing data through ViewData
is not good idea. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将视图所需的所有数据包装在特定于该视图的模型中。这样做的好处是,您还可以在模型中包含搜索条件,该模型最初为空,但是当您发布搜索时,模型将自动包含您的搜索条件,以便您可以在传回结果时重新加载它。这也将有助于保持您在帖子之间的状态。
这还允许您的所有视图数据都是类型安全的,而
ViewData
则不然。例如:
当您返回
List
时,搜索条件已经从帖子中填充到您的模型中,因此您的视图可以将搜索条件默认返回到相应的控件(假设您的搜索结果和搜索输入控件位于同一视图上)。例如,在您的帖子中,您将接受
CustomerSearchViewModel
。然后您需要做的就是获取客户列表并将其添加回模型并返回相同的模型。您还可以将验证属性添加到模型属性中,以利用 MVC 中的内置验证。如果您使用
ViewData
传递此数据,则这是不可能的。你还必须考虑“下一个人”。当视图所需的所有数据都位于单个类中时,它会更干净。这样,他们就不必搜索代码来发现是否正在使用
ViewData
以及实际上在其中传递了哪些数据。ViewData 仍然是传递数据的一个选项,但如果可能的话,我会尽量减少使用它。
You should wrap all your data that is required by you view in a model specific to that view. The advantage to this is you could also include your search criteria in the model which would be empty at first but when your search posted, the model would automatically contain your search criteria so you could reload it when passing back the results. This will help maintain your state between post's as well.
This also allows all your view's data to be type safe where
ViewData
would not be.Eg:
When you return back the
List<Customer>
the search criteria would already be filled in your model from the post so your view can default the search criteria back to the corresponding controls (assuming your search results and search inputs controls are on the same view).For example, in your post you would accept a
CustomerSearchViewModel
. Then all you need to do is get your list of customers and add it back to the model and return the same model.You could also add the validation attributes to your model properties to leverage the built in validation in MVC. This would not be possible if you were using
ViewData
to pass this data around.You have to also consider the 'next guy'. It's cleaner when all the data that the view requires is located in a single class. This way they don't have to hunt through the code to discover if
ViewData
is being used and what data is actually being passed around in it.ViewData
is still an option for passing data but I try to minimize the use of it if at all possible.不要只将项目列表传递给您的视图,而是创建一个包含项目列表和您可能需要的任何其他数据的类,即 ViewModel。
Rather than passing just a list of items to your View, create a class which contains your list of items and any other data you might need, i.e. a ViewModel.