views:

44

answers:

2

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?

+1  A: 

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.

Tim
That means I would have to cast objects which is not a good way of doing ASP.NET MVC.
Alex
Then you could make your view model a subclass of your model and add the extra properties, but retain the validation of the base class.
Tim
Thanks! Not it works great. Very easy solution. (Please update your comment so other people can see how this problem was solved.)
Alex
+1  A: 

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.

Sohnee
What does it mean, "to flatten the model" ?
Alex