ASP.NET MVC:将多个对象传递到视图,包括验证模型
我喜欢使用模型进行验证
<!-- ViewPage -->
<%@ Page Language="C#" Inherits="ViewPage<TopicModel>" %>
...
<%= Html.TextBoxFor(m => m.Title) %>
...
<%= Html.TextBoxFor(m => m.Description) %>
// Controller
[HttpPost]
public ActionResult NewTopic(TopicModel model)
{
// validate
}
它效果很好,但是当我需要传递额外的数据时,我需要创建一个新的 ViewModel 类,并且我失去了灵活性。
<!-- ViewPage -->
<%@ Page Language="C#" Inherits="ViewPage<TopicViewModel>" %>
<%= Model.SomethingImportant %>
...
<%= Html.TextBoxFor(m => m.TopicModel.Title) %> // UGLY, I get name="TopicViewModel.TopicModel.Title"
...
<%= Html.TextBoxFor(m => m.TopicModel.Description) %> // UGLY, same thing
// Controller
[HttpPost]
public ActionResult NewTopic(TopicViewModel model)
{
// validate
var validationModel = model.TopicModel; // UGLY
}
我怎样才能让它变得更容易、更好看?
I like using Models for validation
<!-- ViewPage -->
<%@ Page Language="C#" Inherits="ViewPage<TopicModel>" %>
...
<%= Html.TextBoxFor(m => m.Title) %>
...
<%= Html.TextBoxFor(m => m.Description) %>
// Controller
[HttpPost]
public ActionResult NewTopic(TopicModel model)
{
// validate
}
It works great, but when I need to pass additional data, I need to create a new ViewModel class and I loose the flexibility.
<!-- ViewPage -->
<%@ Page Language="C#" Inherits="ViewPage<TopicViewModel>" %>
<%= Model.SomethingImportant %>
...
<%= Html.TextBoxFor(m => m.TopicModel.Title) %> // UGLY, I get name="TopicViewModel.TopicModel.Title"
...
<%= Html.TextBoxFor(m => m.TopicModel.Description) %> // UGLY, same thing
// Controller
[HttpPost]
public ActionResult NewTopic(TopicViewModel model)
{
// validate
var validationModel = model.TopicModel; // UGLY
}
How can I make it easier and better looking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否考虑过使用 ViewData 字典来存储模型之外的附加数据?
更新 或者,使视图模型成为模型的子类并添加额外的属性,但保留基类的验证。
Have you considered using the ViewData dictionary for your additional data outside of the model?
Update Alternatively, make your view model a subclass of your model and add the extra properties, but retain the validation of the base class.
你说的第二个例子看起来很丑,但实际上是比使用 ViewData 更好的方法。
模型的想法是它包含视图渲染时所需的“东西” - 因此它是放置视图所需的所有数据项的完美位置。
如果您确实对命名约定(框架使用该约定从表单帖子重新填充您的模型)感到不舒服,您可以展平模型。这将为每个项目提供“漂亮”的名称,但会无缘无故地增加大量工作。
Your second example, which you say looks ugly, is actually a better way to do things than using ViewData.
The idea of a model is that it contains the "stuff" the view needs when it renders - so it is the perfect place to put all the data items the view needs.
If you are really offended by the naming convention (which is used by the framework to re-populate your model from a form post) you could flatten the model. This would give you "pretty" names for each item, but would be a lot of work for no reason.