ASP.NET MVC: Passing several objects to the view including a validation model
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?
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.
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.
精彩评论